javascript JQuery 转义撇号和双撇号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4987895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:34:40  来源:igfitidea点击:

JQuery escape apostrophes and double apostrophes?

javascriptjqueryhtml

提问by xiatica

I want to use JQ to print to a div on my page. The string I want to print with contains HTML including apostrophes and double apostrophes.

我想使用 JQ 打印到我页面上的 div。我想打印的字符串包含 HTML,包括撇号和双撇号。

Is there a plugin or function to escape this so that the string doesnt break the js variable? There may be the case that I can't escape all of the apostrophes and double apostrophes in the incoming data using a backslash, so I'm looking for a function that can do it.

是否有插件或函数可以对此进行转义,以便字符串不会破坏 js 变量?可能存在我无法使用反斜杠转义传入数据中的所有撇号和双撇号的情况,因此我正在寻找可以执行此操作的函数。

EG;

例如;

var replacement = 'This content has an apostrophe ' and a double apostrophe "';

$("#overwrite").text(replacement);

TIA

TIA

采纳答案by Mottie

There is no need to escape incoming data, as it is already a string.

不需要转义传入的数据,因为它已经是一个字符串。

The only reason you need to escape apostrophes and double apostrophes in JavaScript source is due to the fact the JavaScript engine has to determine where the string starts and ends.

您需要在 JavaScript 源代码中转义撇号和双撇号的唯一原因是 JavaScript 引擎必须确定字符串的开始和结束位置。

For instance, assuming you have a div#sourcecontaining the text "Hi there, what's up!", it is perfectly safe to do $("#overwrite").text($("#source").text()).

例如,假设您有一个div#source包含 text "Hi there, what's up!",那么这样做是完全安全的$("#overwrite").text($("#source").text())

回答by Mottie

If you wanted to type out a string that is assigned to a variable like in your example above, then just escape it yourself.

如果您想输入一个分配给变量的字符串,就像上面的示例一样,那么只需自己转义即可。

For example, if I know my data will have apostrophes, then I wrap it in quotes (what you are calling double apostrophes) and use the HTML shortcut for quotes "or you can use a backslash to escape the quote \". Either way works. So your example above would become:

例如,如果我知道我的数据会有撇号,那么我将它用引号括起来(你所说的双撇号)并使用 HTML 快捷方式来引用引号,"或者你可以使用反斜杠来转义引号\"。无论哪种方式都有效。所以你上面的例子会变成:

var replacement = "This content has an apostrophe ' and a double apostrophe "";

If the user is typing in the string or you are getting data from a feed, then it would be best to use the javascript replace function to make sure the quotes are escaped, like this:

如果用户正在输入字符串或者您正在从提要中获取数据,那么最好使用 javascript 替换功能来确保引号被转义,如下所示:

var text = $("input").val().replace(/\"/g,""");