0
var Value="!@#$'&\";
 if (value.indexOf("'") > 0) {
        value = value.replace(/'/g, "'"); 

    }

All Text is replaced except last character "\". How do i replace it with same.

2
  • 1
    SyntaxError: unterminated string literal. Please add proper code. Commented Apr 26, 2016 at 8:01
  • Actually all characters are passed through except \. When i enter \ ,it throws error Commented Apr 26, 2016 at 8:03

3 Answers 3

1

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) + ';';
});
Sign up to request clarification or add additional context in comments.

Comments

1

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) + ';';
});

1 Comment

Thank you for the updated range. I have been bashing my head against a wall about why my s characters were getting encoded.
0

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= "!@#$'&\\";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.