Use PHP functions in JavaScript

JavaScript addslashes

Escapes single quote, double quotes and backslash characters in a string with backslashes

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
function addslashes (str) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/addslashes    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
     return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}
external links: original PHP docs | raw js source

Examples

Running

1
addslashes("kevin's birthday");

Should return

1
'kevin\'s birthday'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have addslashes goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
30 Jun '09 Permalink

q  @Denny: Thanks for the report. I've fixed it in SVN. (use \u0000 instead--"\u" indicates a 4-digit hexadecimal Unicode sequence and \0 was a shortcut for this)

Gravatar
Denny Wardhana
30 Jun '09 Permalink

q   Under "Strict Warnings" setup,

1
/\0/g

produces Warning: non-octal digit in an escape sequence that doesn't match a back-reference.

How to remove that warning (and the function still working of course)?

Gravatar
Julien Paquit
23 Sep '08 Permalink

q  Kevin : you are totally right. That was just a tip ;)

Gravatar
Kevin van Zonneveld
21 Sep '08 Permalink

q  @ Julien Paquit: Thank you but I believe PHP does not do that automatically? If not, then we should not either, because we may surprise developers & cause unexpected output.

Gravatar
Julien Paquit
21 Sep '08 Permalink

q   Very useful code ! Because of some scripting needs (and compatibility), I add this portion of code to the original one :

1
return (str+'').replace(/(["])/g, """).replace(/([\\'])/g, "\\$1").replace(/\0/g, "\\0");


Now I am able to pass recursively parameters without errors.

Gravatar
Kevin van Zonneveld
27 Aug '08 Permalink

q  @ Nate & Onno Marsman: Awesome job guys! I have been fooled by my tester for a long time. Addslashes has ben updated, and you have been credited accordingly. I've also changed the new testsuite to support addslashes behaviour.

Gravatar
Onno Marsman
8 Aug '08 Permalink

q   It's probably also a good idea to convert str to a string to make sure .replace exists.
addslashes(6) does work in PHP but not in this function

1
return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");

Gravatar
Nate
22 Jul '08 Permalink

q   I couldn't get the function to work at first. I made some changes, and here is what I came up with:

1
return str.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");


Also, the example should read,
"kevin\\\'s birthday" because the \' becomes '. That is why it appears to work in the tester script.

Gravatar
Kevin van Zonneveld
31 May '08 Permalink

q  @ Dudi: That's just my blog messing up 'addslashes'. Fixed though.

Gravatar
Dudi
30 May '08 Permalink

q  It doesn't seem like the function works. And the example is wrong again. ;-)

Gravatar
Sean Gallagher
24 May '08 Permalink

q   Here is another quicky but good add slashes function!

P.S. I could not get your function to work.

1
2
3
4
56
7
8
9
function addslashes(str)
{
  // http://www.atlwebsite.com
 // By Sean Gallagher
 // Example: addslashes('what "ya\'ll" doing?') // Returns: what \"ya\'ll\" doing?
 str = str.replace(/'/g,"\\'");
 return str.replace(/"/g,'\\"');
}

Gravatar
Kevin van Zonneveld
13 Apr '08 Permalink

q  @ Jonas Raoni: I believe your proposal has the same regex, only here it's singlequoted for compatbility with Dean Edwards packer.

Gravatar
Jonas Raoni
12 Apr '08 Permalink

q   It's missing the "\" escape.

return str.replace(/(["'\\])/g, "\\$1").replace(/\0/g, "\\0") ;

Or

return str.replace(/(["'\\\0])/g, function(_, n){
return "\\" + (n == "\0" ? "0" : n);
});

Gravatar
Kevin van Zonneveld
1 Mar '08 Permalink

q  @ Martin: Fixed!

Gravatar
Kevin van Zonneveld
28 Feb '08 Permalink

q  @ Martin: Thanks for noticing. If you look at the source code, you see that the example is correct. But my blog probably filters out the backslash again. I'll look into it!

Gravatar
Martin
27 Feb '08 Permalink

q  example 1 (the only one) on this page is incorrect, in that it doesn't actually add the slash. hehe.

Gravatar
Kevin van Zonneveld
23 Jan '08 Permalink

q  @ Ates Goral: Processed.

Gravatar
Ates Goral
23 Jan '08 Permalink

q   Additional test case:

1
2
// *     example 2: addslashes("\"'\\\0");
    // *     returns 2: "\\\"\\\'\\\\\\\0"

Gravatar
Ates Goral
23 Jan '08 Permalink

q   First, just a nitpick:

A set of characters can be used instead of the ORs:

1
return str.replace(/(["'\\])/g, "\\$1");


To add support for NUL:

1
return str.replace(/(["'\\])/g, "\\$1").replace(/\0/g, "\\0");

Gravatar
Kevin van Zonneveld
22 Jan '08 Permalink

q  @ booeyOH: It sure is! Thank you!

Gravatar
booeyOH
21 Jan '08 Permalink

q   preg_quote() function for adding slashes to RegEx

Not sure if it is out there, but needed something quick, hope its helpful

1
2
3
4
56
7
8
9
1011
12
function preg_quote( str ) {
        var quote_chars = ["\\", ".", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":"];
        var return_val = str;
        
        for(var i=0;i<quote_chars.length;i++)                {
                eval("var pattern = /\\"+quote_chars[i]+"/gi");
                return_val = return_val.replace(pattern, chr(92)+quote_chars[i]);
                }
                return return_val;
}


Contribute a New function

Download

Download

There is a wide variety of packages if the default doesn't suit you.
You can also compile your own package to avoid any overhead.

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !

RSS

Tweets

Comments

Who uses php.js

If you use php.js, let us know and get linked.

Progress

php.js is complete for 83.7%

php.js on

Discuss php.js' future at Google Groups
Help improve php.js on github



Powered by php.js
Stats