Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
"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 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". – Steve Harrison Apr 21 '09 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. – Jo Liss May 11 at 19:55

2 Answers

up vote 15 down vote accepted

http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
share|improve this answer
4  
So then the answer is "no, there is no built-in function like PHP's addslashes" – Rick Copeland Apr 20 '09 at 23:58
Yes, that is the answer. – Paolo Bergantino Apr 21 '09 at 0:04
Good, I'll add this function to my [ever growing] collection of functions/methods that are missing from JavaScript... Thanks! – Steve Harrison Apr 21 '09 at 0:55

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());
share|improve this answer
1  
Worth noting that extending native javascript objects is considered by many bad practice. – Benjamin Gruenbaum Feb 8 at 11:07
2  
@BenjaminGruenbaum: if you are afraid of conflicts you can add if(!String.prototype.addSlasches) before extending – Marco Demaio Feb 12 at 19:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.