JavaScript preg_quote
Quote regular expression characters plus an optional character
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 | function preg_quote (str, delimiter) { // Quote regular expression characters plus an optional character // // version: 1008.1718 // discuss at: http://phpjs.org/functions/preg_quote // + original by: booeyOH // + improved by: Ates Goral (http://magnetiq.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: Brett Zamir (http://brett-zamir.me) // * example 1: preg_quote("$40"); // * returns 1: '\$40' // * example 2: preg_quote("*RRRING* Hello?"); // * returns 2: '\*RRRING\* Hello\?' // * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:"); // * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:' return (str+'').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\'+(delimiter || '')+'-]', 'g'), '\\$&'); } |
Examples
» Example 1
Running
1 | preg_quote("$40"); |
Should return
1 | '\$40' |
» Example 2
Running
1 | preg_quote("*RRRING* Hello?"); |
Should return
1 | '\*RRRING\* Hello\?' |
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 preg_quote goodness in JavaScript.
[CODE="Javascript"]
function preg_replace_callback(reg, cbck, str){
return str.replace(REGEXP, function(arguments){return window[cbck](arguments);});
}
[/CODE]
After looking at the implementation of addslashes(), I realized that this could have been simply achieved with:
[CODE="Javascript"]
return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
[/CODE]
I don't know why I chose to use a replacement function in the first place :)
Here's my take:
[CODE="Javascript"]
function preg_quote(str) {
// * example 1: preg_quote("*RRRING* Hello?");
// * returns 1: "\\*RRRING\\* Hello\\?"
// * example 2: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 2: "\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:"
return str.replace(/[\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:]/g, function(c) { return "\\" + c; });
}
[/CODE]


Kevin van Zonneveld
13 Apr '08