Search code examples
javascripthtmlstringstring-formatting

Adding variables in string JS


I am using a string to store some HTML. However, the string needs to have some variables. The method I am using to input this variables is encountering a problem. There are quotes in my HTML. Therefore the string is cutting short where I don't want it to.

base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"

However, I am getting this error.

'vote(' Uncaught SyntaxError: Unexpected end of input

Even if I remove the 2 single quotes in the brackets, I am getting an error.

'vote(Iron Man); return false': Uncaught SyntaxError: missing ) after argument list. NOTE: Iron Man is the value of data[i].

Thanks in advance!


Solution

  • You've got a ' and a " flipped around.

    base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"
    
                                                                   ^^---- flip these two
    



    Template literals can make complicated string concatenations much more readable and less error-prone as it would eliminate the need for most of the " double quotes in your code sample:

    base = `<h2>${data[i]}</h2><br><button onclick="vote('${data[i]}'); return false">Vote for ME!</button>`