[英]How to replace HTML special character in javascript?
var Value="!@#$'&\";
if (value.indexOf("'") > 0) {
value = value.replace(/'/g, "'");
}
All Text is replaced except last character "\\". 除最后一个字符“ \\”外,所有文本均被替换。 How do i replace it with same.
我如何用相同的东西代替它。
This is the currently 'accepted' code to convert all (or a range of them) possible unicode characters to their equivalent HTML entity: 这是当前“接受”的代码,用于将所有 (或其中一个范围)所有可能的unicode字符转换为它们等效的HTML实体:
var value = "!@#$'&\\";
value = value.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
存在语法错误,该错误一旦修复也将替换\\
字符:您需要额外的反斜杠,因为反斜杠是特殊字符,需要转义。
var value= "!@#$'&\\";
I have new information about this solution from @MarcoS: 我从@MarcoS获得了有关此解决方案的新信息:
var value = "!@#$'&\\";
value = value.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
I am not sure when it started, but as of today 2019/07/10, this code will not work in chrome, but it does work in firefox/safari. 我不确定它什么时候开始,但是从今天开始2019/07/10,此代码将无法在chrome中使用,但在Firefox / safari中可以使用。 It will cause the lowercase 's' character to trip the regex and output as encoded
s
这将导致小写的's'字符触发正则表达式并输出为已编码的
s
A coworker of mine found that this character \ſ
, now in the unicode standard, and causes this code to act strangely: http://www.fileformat.info/info/unicode/char/17f/index.htm 我的一个同事发现这个字符
\ſ
(现在已成为unicode标准),并导致该代码行为异常: http : //www.fileformat.info/info/unicode/char/17f/index.htm
If you instead use the following, it should work in all browsers: 如果改为使用以下内容,则它应在所有浏览器中都可以使用:
var value = "!@#$'&\\";
value = value.replace(/[\u00A0-\u017e\u0180-\u9999]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.