Skip to content Skip to sidebar Skip to footer

Regex Gives Error For Certain Chars

I came across this pen at codePen, and found a bug. If you type in the following chars in the searchbox: ), (, [, +, \, *, ? I get the following error (I entered each char separa

Solution 1:

The answer to this question requires a familiarity with Regular Expressions. From http://www.regular-expressions.info:

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *.txt to find all text files in a file manager. The regex equivalent is .*\.txt$.

Regular expressions are put together using a variety of special characters, all of which have different meanings. The characters that, as you discovered, cause the search box to break are considered special characters in regular expressions. For example, ( and ) are used to indicate "groups" of characters within the regular expression.

To briefly answer the question of "how to fix it": the easy way would be to add a \ in front of any special characters in this.value. \ is a special character which causes the character that immediately follows it to be considered as a "non-special" character.

e.g.

var escapedValue = this.value.replace(")", "\\)");
escapedValue = escapedValue.replace("(", "\\(");
escapedValue = escapedValue.replace("[", "\\[");
escapedValue = escapedValue.replace("+", "\\+");
escapedValue = escapedValue.replace("\\", "\\\\)");
escapedValue = escapedValue.replace("*", "\\*");
escapedValue = escapedValue.replace("?", "\\?");
var rgx = new RegExp(escapedValue, "i");

Note that this code snippet won't completely fix the problem (the list of special characters isn't exhaustive), and it's not a very elegant solution, but it illustrates the general concept.

Post a Comment for "Regex Gives Error For Certain Chars"