简体   繁体   English

在JavaScript和HTML中转义撇号(单引号)字符

[英]Escaping apostrophe (single quote) character in javascript and html

I have a following situation: 我有以下情况:

I compose a string in javascript that include apostrophe character. 我在javascript中编写了一个包含撇号字符的字符串。 That string is actually html code that is later attached to html using innerHTML method. 该字符串实际上是html代码,后来使用innerHTML方法附加到html。 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: 然后,将这个字符串插入到这样的html元素中:

dataHolder.innerHTML = str;

I've tried to escape ' character with &apos; 我试图逃跑'字用&apos; , &#39; &#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 \'但是所有这些在调用innerHTML方法后都呈现为' ,因此,当通过单击链接调用上述示例中的方法foo时,我总是收到JavaScript错误,说: Uncaught SyntaxError: missing ) after argument list出现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 \\ : 你需要有两个'"你的字串,所以你将需要第三个办法delcare一个字符串,您可以使用模板字符串为。声明你ba'r字符串作为模板字符串,并使用反斜杠逃脱它的撇号\\

 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>`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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