86

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

7
  • 9
    "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) Commented Apr 21, 2009 at 0: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". Commented Apr 21, 2009 at 1: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. Commented May 11, 2013 at 19:55
  • 4
    Down below is an answer by @Storm : Use JSON.stringify. Isn't that a great alternative? Commented Jul 2, 2014 at 11:24
  • 1
    JavaScript: Escaping Special Characters Commented Aug 30, 2014 at 5:14

5 Answers 5

112

You can also try this for the double quotes:

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
Sign up to request clarification or add additional context in comments.

9 Comments

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?
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\""'.
One downside is that things like \x00 aren't supported, and are instead represented with the lengthier \u0000.
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.
Beautiful, elegant, efficient. Used this to debug some parsers I was writing - amazingly useful
|
106

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

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

7 Comments

So then the answer is "no, there is no built-in function like PHP's addslashes"
Good, I'll add this function to my [ever growing] collection of functions/methods that are missing from JavaScript... Thanks!
Don’t. It’s a terrible solution.
Could you please explain the '\u0000' replace? Thank you.
\u0000 is a null character. I'm not certain why it is necessary to remove.
how can we check if the string contains a slash before adding a new one
|
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.");

4 Comments

Worth noting that extending native javascript objects is considered by many bad practice.
@BenjaminGruenbaum: if you are afraid of conflicts you can add if(!String.prototype.addSlasches) before extending
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
@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.
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.

1 Comment

The string would not be readable: "This is a demo string with 'single-quotes'" becomes "%3C%3EThis%20is%20a%20demo%20string%20with%20'single-quotes'"
-1

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));

2 Comments

careful with using escape(), it is in Annex B, which means not deprecated but undesired side-effects. Read more at MDN
it is deprecated now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.