82

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

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • 8
    "Need escaping" for what purpose? There are many different reasons to escape strings, and the correct way to do it can be different depending on the goal. (e.g., PHP's addslashes() is usually the wrong solution when SQL is involved: a better solution is parameterized queries) – Miles Apr 21 '09 at 00:19
  • I'm actually developing an Apple Dashboard Widget, and I want my strings to be properly escaped before using them in Terminal commands via "widget.system". – Steve Harrison Apr 21 '09 at 01:17
  • @SteveHarrison This is probably unsafe. There will be ways to break out of this, enabling arbitrary code execution. Shells do weird things with their input. If you plan on passing untrusted data, the only way to avoid having to do backflips for `system` is using some other function instead that allows you to pass unescaped parameters. – Jo Liss May 11 '13 at 19:55
  • 4
    Down below is an answer by @Storm : `Use JSON.stringify`. Isn't that a great alternative? – user Jul 02 '14 at 11:24
  • 1
    [JavaScript: Escaping Special Characters](http://www.the-art-of-web.com/javascript/escape/) – Damodaran Aug 30 '14 at 05:14
  • PHP has addslashes to add backslashes? Why am I not surprised? – rsp Apr 04 '18 at 22:12

5 Answers5

104

You can also try this for the double quotes:

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
Knu
  • 14,806
  • 5
  • 56
  • 89
Storm
  • 1,049
  • 1
  • 7
  • 2
  • 4
    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? – user Jul 02 '14 at 11:23
  • 1
    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\""'. – dlaliberte Feb 03 '15 at 20:59
  • 1
    One downside is that things like `\x00` aren't supported, and are instead represented with the lengthier `\u0000`. – gengkev Dec 13 '15 at 18:27
  • 10
    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. – Hashbrown May 24 '16 at 10:42
  • 1
    Beautiful, elegant, efficient. Used this to debug some parsers I was writing - amazingly useful – stevendesu Jan 08 '17 at 14:22
  • @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. – sleske Mar 17 '17 at 11:33
  • really rocks, bro ! – NGloom Nov 17 '20 at 06:45
  • This sucks in a node environment – Israel Obanijesu Mar 18 '21 at 08:07
  • @gengkev `\u0000` could be replaced with `\x00` by `JSON.stringify(str).replaceAll(/\\u00([\da-f]{2})/g, '\\x$1')` – traxium May 05 '22 at 19:29
104

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

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
40

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.");
SharpC
  • 6,974
  • 4
  • 45
  • 40
Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
  • 8
    Worth noting that extending native javascript objects is considered by many bad practice. – Benjamin Gruenbaum Feb 08 '13 at 11:07
  • 6
    @BenjaminGruenbaum: if you are afraid of conflicts you can add `if(!String.prototype.addSlasches)` before extending – Marco Demaio Feb 12 '13 at 19:11
  • 1
    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 – B T Aug 06 '13 at 06:05
  • 4
    @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. – Marco Demaio Aug 12 '13 at 14:27
2

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.

tcmoore
  • 1,129
  • 1
  • 12
  • 29
0

You can also use this

let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
Renish Gotecha
  • 2,232
  • 22
  • 21
  • 2
    careful with using `escape()`, it is in Annex B, which means not deprecated but undesired side-effects. Read more at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape) – Mario Aug 11 '21 at 14:19