简体   繁体   中英

Escaping apostrophe (single quote) character in javascript and html

I have a following situation:

I compose a string in javascript that include apostrophe character. That string is actually html code that is later attached to html using innerHTML method. So the code looks something like this:

var str = '<a href="javascript:foo("ba'r")">link</a>'; (argument of the foo function is string)

And after that, this string is inserted into some html element like this:

dataHolder.innerHTML = str;

I've tried to escape ' character with &apos; , &#39; and \' but all of that is rendered as ' after innerHTML method is called, so when the method foo from the example above is called by clicking on link I always get javascript error saying: Uncaught SyntaxError: missing ) after argument list

You need to have both ' and " in your string, so you will need a third way to delcare a string, you can use template strings for that. Declare your ba'r string as a template string and escape its apostrophe using a backslash \\ :

 document.querySelector('#myDiv').innerHTML = '<a href="javascript:foo(`ba\\'r`)">link</a>'; function foo(data) { console.log(data); } 
 <div id="myDiv"></div> 

use \\' instead of ' inside the string, so it should be

var str = '<a href="javascript:foo(ba\\'r)">link</a>';

However, this code is just correct in string format aspect. I think what you want could be

var str = '<a href="javascript:foo(\\'bar\\')">link</a>';

您也可以使用反引号`来避免此问题:

var str = `<a href="javascript:foo(ba'r)">link</a>`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM