How to escape all special characters in javaScript.
We are using this, but it's not working:
<input type = "text" value="' }{ " : ? > < \ ] [ ' ; / . ,">
Escape Characters Use the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.
To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”. For example: alert( "Chapter 5.1".
You need just to exchange "
with "
.
A good idea is to take some more HTML entities:
<
replace with <
>
replace with >
<input type = "text" value="' }{ " : ? > < \ ] [ ' ; / . ,">
By using the browsers DOM you can let the browser do the work for you.
Make a HTML node, append a text node to it and put in the text node the html code you wish to escape.
Only for double quotes you might need to account by doing a replace on them to "
and single quotes to '
function htmlspecialchars(str) {
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML.replace(/"/g,'"').replace(/'/g,''');
}
console.log(htmlspecialchars("<html>"));
console.log(htmlspecialchars("<!DOCTYPE=\"RUBBISH\">"));
console.log(htmlspecialchars("' }{ \" : ? > < \\ ] [ ' ; / . ,"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With