views:

640

answers:

2

Hello,

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

Thanks,

Steve

+6  A: 

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

function addslashes( str ) {
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}
Paolo Bergantino
So then the answer is "no, there is no built-in function like PHP's addslashes"
Rick Copeland
Yes, that is the answer.
Paolo Bergantino
Good, I'll add this function to my [ever growing] collection of functions/methods that are missing from JavaScript... Thanks!
Steve Harrison
+4  A: 

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, "\\$1").replace(/\0/g, "\\0"); 
} 

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

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