Escaping Strings in JavaScript

139,866

Solution 1

http://locutus.io/php/strings/addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

Solution 2

You can also try this for the double quotes:

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);

Solution 3

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

Solution 4

Use encodeURI()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.

Share:
139,866
Steve Harrison
Author by

Steve Harrison

Updated on July 05, 2022

Comments

  • Steve Harrison
    Steve Harrison almost 2 years

    Does JavaScript have a built-in function like PHP's addslashes (or addcslashes) function to add backslashes to characters that need escaping in a string?

    For example, this:

    This is a demo string with 'single-quotes' and "double-quotes".

    ...would become:

    This is a demo string with \'single-quotes\' and \"double-quotes\".

  • Rick Copeland
    Rick Copeland about 15 years
    So then the answer is "no, there is no built-in function like PHP's addslashes"
  • Steve Harrison
    Steve Harrison about 15 years
    Good, I'll add this function to my [ever growing] collection of functions/methods that are missing from JavaScript... Thanks!
  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 11 years
    Worth noting that extending native javascript objects is considered by many bad practice.
  • Marco Demaio
    Marco Demaio about 11 years
    @BenjaminGruenbaum: if you are afraid of conflicts you can add if(!String.prototype.addSlasches) before extending
  • B T
    B T over 10 years
    Exactly how does that help? If you're expecting one addSlashes function and you get another one, you're likely gonna end up with a really hard to find bug. Better to throw an exception if there's a conflict
  • Marco Demaio
    Marco Demaio over 10 years
    @BT: well an addSlashes func is actually supposed to add slashes in one way or another. Anyway i updated the code in the answer to reflect your suggestion.
  • Tom Pažourek
    Tom Pažourek about 10 years
    Could you please explain the '\u0000' replace? Thank you.
  • user
    user almost 10 years
    This is an excellent answer. I'm surprised there's no 'obvious' built in method to escape quotes but this does the job. Are there any caveats?
  • dlaliberte
    dlaliberte about 9 years
    The result of JSON.stringify() with a string is a string with double quotes around your string. It is the string that, when evaluated, will result in the same string you started with. So JSON.stringify('my string with "quotes"') returns the string: "my string with \"quotes\"", which you might enter in JavaScript as '"my string with \"quotes\""'.
  • gengkev
    gengkev over 8 years
    One downside is that things like \x00 aren't supported, and are instead represented with the lengthier \u0000.
  • Hashbrown
    Hashbrown almost 8 years
    This catches newlines, tabs, et cetera too, which the other answers ignored. And without it turning into a list of all possible special characters taboot. This is the best answer. Worth noting that it only escapes " and not ', though.
  • stevendesu
    stevendesu over 7 years
    Beautiful, elegant, efficient. Used this to debug some parsers I was writing - amazingly useful
  • sleske
    sleske about 7 years
    @Hashbrown: Yes, that's true. That is because it creates JSON strings, and JSON strings are always delimited by double quotes (") according to spec. In JavaScript, ' is a valid string delimiter, too, but not in JSON.
  • N-ate
    N-ate over 6 years
    \u0000 is a null character. I'm not certain why it is necessary to remove.
  • NGloom
    NGloom over 3 years
    really rocks, bro !
  • Israel Obanijesu
    Israel Obanijesu over 3 years
    how can we check if the string contains a slash before adding a new one
  • Israel Obanijesu
    Israel Obanijesu about 3 years
    This sucks in a node environment
  • Mario
    Mario over 2 years
    careful with using escape(), it is in Annex B, which means not deprecated but undesired side-effects. Read more at MDN
  • traxium
    traxium almost 2 years
    @gengkev \u0000 could be replaced with \x00 by JSON.stringify(str).replaceAll(/\\u00([\da-f]{2})/g, '\\x$1')