Reputation: 63
var Value="!@#$'&\";
if (value.indexOf("'") > 0) {
value = value.replace(/'/g, "'");
}
All Text is replaced except last character "\". How do i replace it with same.
Upvotes: 0
Views: 1525
Reputation: 106
I have new information about this solution from @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. It will cause the lowercase 's' character to trip the regex and output as encoded s
A coworker of mine found that this character \u017f
, now in the unicode standard, and causes this code to act strangely:
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) + ';';
});
Upvotes: 1
Reputation: 10849
There is a syntax error, that once fixed will also replace the \
character:
You need an extra backslash because backslash is a special character and needs to be escaped.
var value= "!@#$'&\\";
Upvotes: 0
Reputation: 17711
This is the currently 'accepted' code to convert all (or a range of them) possible unicode characters to their equivalent HTML entity:
var value = "!@#$'&\\";
value = value.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
Upvotes: 1