How to escape ",< and all special characters in JavaScript
11,102
Solution 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="' }{ " : ? > < \ ] [ ' ; / . ,">
Solution 2
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("' }{ \" : ? > < \\ ] [ ' ; / . ,"))
Author by
vinay kumar
Updated on June 11, 2022Comments
-
vinay kumar almost 2 years
How to escape all special characters in javaScript.
We are using this, but it's not working:
<input type = "text" value="' }{ " : ? > < \ ] [ ' ; / . ,">