Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape string for use in Javascript regex [duplicate]

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?

like image 757
too much php Avatar asked Aug 10 '10 05:08

too much php


People also ask

How do you escape a string 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.

Is there a regexp escape function in JavaScript?

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.

How do you escape a string in 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.

Do you need to escape dash in regex?

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).


1 Answers

Short 'n Sweet (Updated 2021)

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, '$$$$'); } 

Example

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.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");  >>> "\/path\/to\/resource\.html\?search=query" 

The Long Answer

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") }()); 
like image 128
coolaj86 Avatar answered Sep 22 '22 10:09

coolaj86