Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How to escape all special characters in javaScript.

We are using this, but it's not working:

<input type = "text" value="' }{ " : ? > < \ ] [ ' ; / . ,">
like image 683
vinay kumar Avatar asked Jan 08 '18 13:01

vinay kumar


People also ask

How do you escape special characters?

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.

How do you escape special characters in typescript?

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".


2 Answers

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; \ ] [ ' ; / . ,">
like image 105
Nina Scholz Avatar answered Oct 14 '22 05:10

Nina Scholz


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("' }{ \" : ? > < \\ ] [ ' ; / . ,"))
like image 28
Tschallacka Avatar answered Oct 14 '22 03:10

Tschallacka