jayesh patil
jayesh patil

Reputation: 63

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.

Upvotes: 0

Views: 1525

Answers (3)

draxiom
draxiom

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 &#115; 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

axelduch
axelduch

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

MarcoS
MarcoS

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

Related Questions