Skip to content Skip to sidebar Skip to footer

Problematic Quotes In Javascript Callfunction()

I would like to know how to maintain the ability to have both single and double quotes in text that I am passing to a JavaScript function with callFunction()? All three cases below

Solution 1:

Thank you all for your advice. With it, I have found a workable solution. It appears that using both backslash and HTML Special Characters together will allow it to work. I am not sure why both is required?

<!--Using HTML Special Characters (&#039;) alone will not work--><ahref="#"onClick="callFunction('Robin&#039;s Text')">Robin&#039;s Text</a><br /><br /><!--Using backslash (\) alone will not work--><ahref="javascript: callFunction('Robin\"sText')">Robin"s Text</a><br /><br /><!--But using a combination of both will work!--><ahref="javascript: callFunction('Robin\&#034;s Text')">Robin"s Text</a>

Solution 2:

Assuming that the input for the JS function will be machine-generated, then you should escape the input from the server, then unescape it in the client-side as below:

HTML:

<ahref="#"onclick='callFunction("Robin%27s%20Text")'>Robin's Text</a><br><ahref="#"onclick='callFunction("Robin%22s%20Text")'>Robin"s Text</a>

JS:

function callFunction(text){
    alert(decodeURIComponent(text));
}

See the working code at:

JSFiddle

Post a Comment for "Problematic Quotes In Javascript Callfunction()"