How to escape ",< and all special characters in JavaScript

11,102

Solution 1

You need just to exchange " with &quot;.

A good idea is to take some more HTML entities:

  • < replace with &lt;
  • > replace with &gt;

<input type = "text" value="' }{ &quot; : ? &gt; &lt; \ ] [ ' ; / . ,">

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 &quot; and single quotes to &#39;

function htmlspecialchars(str) {
  var div = document.createElement('div');
  var text = document.createTextNode(str);
  div.appendChild(text);
  return div.innerHTML.replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

console.log(htmlspecialchars("<html>"));
console.log(htmlspecialchars("<!DOCTYPE=\"RUBBISH\">"));
console.log(htmlspecialchars("' }{ \" : ? > < \\ ] [ ' ; / . ,"))

Share:
11,102
vinay kumar
Author by

vinay kumar

Updated on June 11, 2022

Comments

  • vinay kumar
    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="' }{ " : ? > < \ ] [ ' ; / . ,">