0

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?

1
  • htmlString = "<button class='button-icon' value='PLAY' onclick='playAudio(\"more strings \")'></button>"; Commented Nov 25, 2016 at 23:25

4 Answers 4

2

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>

js:

document.getElementById('fooBtn').addEventListener('click', function() {
    playAudio("SP00005");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! Escaping did the trick! An event listener wasn't suitable because the page is dynamic and adds different buttons according to the content loaded by the database. Thanks a lot!!
0

You can escape " with \"'

Example test = "Hello, I am \"Steve\""

which resolves to: Hello, I am "Steve"

Comments

0

You will need to do this way, using \" inside playAudio():

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

Comments

0

You can also use back ticks. This will allow you to build the string however you want without escape characters

var string = `<button class='button-icon' value='PLAY' onclick='playAudio('SP00005')'></button>`;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

3 Comments

Starting with es6, no IE support, but a good way of doing this nowadays
Thanks for that caveat baao !
I hate to say it, I'm using template strings all the time.. But everything new breaks IE... :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.