使用转义函数会抛出js错误,因为文本中存在特殊字符

Using escape function throws js error because special characters are present in text

本文关键字:因为 文本 特殊字符 存在 错误 js 转义 函数      更新时间:2023-09-26

示例如下:-

var encdata= escape('They're good at coding."Super". Its great!');

现在出现了错误,因为它在最后找到了结束撇号

如果我的代码与

相同,它将工作
var encdata= escape('They re good at coding."Super".Its great!');

同样,如果我使用双引号并给出

var encdata= escape("They're good at coding."Super".Its great!");

它会对"super"抛出错误,但不会对" they're "抛出错误。

所以,当我的文本包含双引号和撇号时,它应该工作。

并且我不能将我的文本包装为"text"或"text"。

所以,我需要一个替代的解决方案

'''"转义;

var encdata = escape('They''re good at coding."Super".Its great!');
var encdata = escape("They're good at coding.'"Super'".Its great!");

需要使用'"、'":

var encdata= escape("They're good at coding.'"Super'".Its great!");

var encdata= escape('They''re good at coding."Super".Its great!');

您必须使用斜杠'来转义单引号内的撇号,或者双引号内的开引号。

'They''re good at coding."Super". Its great!'
"They're good at coding.'"Super'".Its great!"

对于几乎所有的语言都是如此。在字符中添加斜杠可以让它知道您希望它是一个文字字符,而不是具有特殊含义。