Use PHP functions in JavaScript

JavaScript stripslashes

Strips backslashes from a string

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':                return '\u0000';
            case '':
                return '';
            default:
                return n1;        }
    });
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
stripslashes('Kevin\'s code');

Should return

1
"Kevin's code"

» Example 2

Running

1
stripslashes('Kevin\\\'s code');

Should return

1
"Kevin\'s code"

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 stripslashes 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 Dec '09 Permalink

q  @Robert Hollencamp: yes, thanks, you are correct. Previously fixed in Git, but not yet making it to the site here.

Gravatar
Robert Hollencamp
29 Dec '09 Permalink

q  Line 19 (return '\u000';) causes parse errors in safari and IE; adding an extra 0 (return '\u0000';) seems to fix the problem

Gravatar
Kevin van Zonneveld
10 Jun '09 Permalink

q  @ Rick & Brett Zamir: Well for one thing it isn't part of PHP functions. And that's what we're providing here. If people want to take that functionality and wrap it in something that does provide chaining, they are free to do so, and the namespaced version of php.js would probably be easiest to extend on.

That said, I've seen rumours that PHP6 does support chaining so by the time that it's stable we may have to support it after all :)

Gravatar
Brett Zamir
4 Jun '09 Permalink

q  Hi Rick,

It turns out stripslashes doesn't only strip those next to quotation works, even though addslashes only adds them this way. But it does preserve double-backslashed items and does convert the NULL character. I've optimized the handling to avoid going over the same characters again as well as handled removing backslashes at the end.

As far as string conversion, it seems PHP does convert first to a string (at least with integers), so I think we're ok there.

As far as chaining via the prototype, though that can definitely be convenient, for larger scripts, there is a potential for a clash of implementations (e.g., someone may later override the prototype with their own function, say stripslashes() which say only strips slashes next to quotes). These are kind of like globals and really are to be avoided at least for library projects.

We could still conceivably get chaining of methods, such as jQuery does, by first making our string into an object, for example:

var newStr = $PJ(str).addslashes().str_replace('stuff', '').exit();



...but this would require making a version of PHP.JS where each function returned "this", and we'd need to define the constructor and exit methods. Not sure how popular that would be either, though it could be done.

Gravatar
Rick
3 Jun '09 Permalink

q  I posted that with a bit of haste...

some corrections:

String.prototype.stripslashes = function() {
  return  this.replace(/\\'/g,'\'')
                .replace(/\"/g,'"')
                  .replace(/\\\\/g,'\\')
                    .replace(/\\0/g,'\0');
}
// that can also be added to for htmlentity support. but thats not the point i'm trying to make.

var str = "that\'s everything folks";
str.stripslashes().replace('everything', 'all');
// stripslashes, then demonstrates chainability


Gravatar
Rick Waldron
3 Jun '09 Permalink

q  Just out of curiousity... how come you didn't write these functions as methods of an object?
example:

String.prototype.stripslashes = function() {
  return this.replace('/\0/g', '0').replace('/\(.)/g', '$1')
}



that way you dont have to force it into a string, it can now also be chained... like...

var str = "that's everything folks";
str.stripslashes().replace('everything', 'all');





note... i used the corrected version posted by Onno Marsman below.

Gravatar
Dave Baldwin
29 May '09 Permalink

q  I just had to use this to get rid of a slash "\'" because the single quote was really the htmlentity "'":

str=str.replace(/\\'/g,"'");


Gravatar
Kevin van Zonneveld
17 Dec '08 Permalink

q  @ rezna: Ok as I see it your code only replaces either \ or ' or ", and not any other character that is escaped. Fair enough. But are you sure the previous function didn't work? It didn't give issues in the test suite. Not even with the old implementation and your new sample code.

Gravatar
rezna
15 Dec '08 Permalink

q  stripslashes doesn't work, the implementation should be this

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

and your sample code should be
[CODE="Javascript"]
stripslashes('Kevins\\\'s code')
[/CODE]

Gravatar
Kevin van Zonneveld
6 Oct '08 Permalink

q  @ Onno Marsmann: Fixed, thank you!

Gravatar
Onno Marsman
4 Oct '08 Permalink

q  stripslashes(6) won't work. Fix:

[CODE="Javascript"]
function stripslashes( str ) {
return (str+'').replace('/\0/g', '0').replace('/\(.)/g', '$1');
}
[/CODE]

Gravatar
Kevin van Zonneveld
29 Jan '08 Permalink

q  @ Mickael9: Thanks for your input!

Gravatar
Mickael9
27 Jan '08 Permalink

q  Huh, sorry, I meant stripslashes("\x20"), not stripslashes('\x20')

Gravatar
Mickael9
27 Jan '08 Permalink

q  Hello,

Ates Goral, you're totally wrong !
stripslashes only removes \ it DOES NOT unescapes octal and hexadecimal code sequences, you are experimenting in a wrong way, remember, when you call stripslashes('\x20'), PHP ITSELFS turns \x20 in a space, not your function, read the addslashes manual, it onlty turns ' into \', " into \", \ into \\ and NULL into \0.

Here is the fixedfunction :
[CODE="Javascript"]function stripslashes (str)
{
// http://kevin.vanzonneveld.net
// + improved by: Ates Goral (http://magnetiq.com)
// + fixed by: Mick@el
// * example : stripslashes("Kevin\\\\'s code");
// * returns : 'Kevin\'s code'
return str.replace(/\\0/g, '\0').replace(/\\(.)/g, '$1')
}
[/CODE]

Gravatar
Kevin van Zonneveld
23 Jan '08 Permalink

q  @ Ates Goral: Obviously!

Gravatar
Ates Goral
23 Jan '08 Permalink

q  Thanks Kevin! Err... I want my credits in the function comments (I'm keen on keeping the two medals, at least for a while) ;)

Gravatar
Kevin van Zonneveld
23 Jan '08 Permalink

q  @ Ates Goral: Nicely crafted.

Gravatar
Ates Goral
23 Jan '08 Permalink

q  stripslashes() unescapes octal and hexadecimal ASCII code sequences as well. So we should have instead:

[CODE="Javascript"]
return str.replace(/\\(["'\\])/g, "$1").replace(/(\\(?:[0-7]{1,3}|x[\dA-Fa-f]{1-2}))/g, function(code) { return String.fromCharCode(code); });
[/CODE]

Additional test:
[CODE="Javascript"]
// * example 2: stripslashes("Hello\x20World\41");
// * returns 2: "Hello World!"
[/CODE]


Contribute a New function