rvelbon rvelbon - 6 months ago 48
HTML Question

How do I pass a string within a string within a string?

I have a javascript playAudio() function which expects a string parameter. I can't seem to figure out how to pass a string value as a parameter for this function without breaking out of the string.

htmlString = "<button class='button-icon' value='PLAY' onclick='playAudio()'></button>";

I want to pass the string "SP00005" as a parameter. However I am unable to use inverted commas or apostrophes as these have already been used for the more outer part of my htmlString.

I even tried breaking up formation of htmlString into various steps as illustrated below:

htmlString = "";
htmlString += "<button class='button-icon' value='PLAY' onclick='playAudio(";
htmlString += "SP00005";
htmlString += ")'></button>";

So my question to you is: how do I pass a string within a string which itself is in a string?


One way would be to escape the ".

htmlString = "<button class='button-icon' value='PLAY' onclick='playAudio(\"foo\")'></button>";

The better option is to select the button with javascript, add an eventListener and don't bother about inline js

<button id="fooBtn" class='button-icon' value='PLAY'></button>


document.getElementById('fooBtn').addEventListener('click', function() {