Is there js function that replace xml Special Character with their escape sequence?
16,333
Solution 1
There's an interesting JS library here: Client side HTML encoding and decoding
Solution 2
I have used this:
function htmlSpecialChars(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Solution 3
You could use PHP's htmlspecialchars
from the PHPJS project.
Solution 4
This is similar to Can I escape html special chars in javascript?
The accepted answer there is this:
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
However, if you're using lodash, then I like cs01's answer from that post:
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
Comments
-
Dor Cohen almost 2 years
I search the web alot and didn't find js function that replace xml Special Character with their escape sequence?
Is there something like this?I know about the following:
Special Character Escape Sequence Purpose & & Ampersand sign ' ' Single quote " " Double quote > > Greater than < < Less than
is there more? what about writing hexadecimal value like 0×00,
Is this also a problem?