Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I am trying to build a javascript regex based on user input:
function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search }
But the regex will not work correctly when the user input contains a ?
or *
because they are interpreted as regex specials. In fact, if the user puts an unbalanced (
or [
in their string, the regex isn't even valid.
What is the javascript function to correctly escape all special characters for use in regex?
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
Escaping / makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation. As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases. And yes, it is a disappointing failing that this is not part of standard JavaScript.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
To escape the RegExp itself:
function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }
To escape a replacement string:
function escapeReplacement(string) { return string.replace(/\$/g, '$$$$'); }
All escaped RegExp characters:
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Find & replace a string:
var haystack = "I love $x!"; var needle = "$x"; var safeNeedle = escapeRegExp(needle); // "\\$x" var replacement = "$100 bills" var safeReplacement = escapeReplacement(replacement); // "$$100 bills" haystack.replace( new RegExp(safeNeedle, 'g'), escapeReplacement(safeReplacement), ); // "I love $100 bills!"
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query"); >>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp; (function () { // Referring to the table here: // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp // these characters should be escaped // \ ^ $ * + ? . ( ) | { } [ ] // These characters only have special meaning inside of brackets // they do not need to be escaped, but they MAY be escaped // without any adverse effects (to the best of my knowledge and casual testing) // : ! , = // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g) var specials = [ // order matters for these "-" , "[" , "]" // order doesn't matter for any of these , "/" , "{" , "}" , "(" , ")" , "*" , "+" , "?" , "." , "\\" , "^" , "$" , "|" ] // I choose to escape every character with '\' // even though only some strictly require it when inside of [] , regex = RegExp('[' + specials.join('\\') + ']', 'g') ; escapeRegExp = function (str) { return str.replace(regex, "\\$&"); }; // test escapeRegExp("/path/to/res?search=this.that") }());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With