If ‘[‘ special character is used in regex constructor object, it throws Invalid regular expression: /mat[/: Unterminated character class
function findMatch() {
var string="Find the match";
var text = "Mat[";
string.replace(new RegExp(text, 'gi'), "found")
}
Why this error is occuring and how to solve this?
2
Answers
Regular expressions use the characters
[]
to identify a character class– to match any character within the brackets. If you want to use either of those bracket characters as a literal, then you must escape it with a backslash. Your goal should be the regular expression:You’ll also need to escape the backslash itself to convert from the string to a regular expression. Thus, your code should be:
The error occurs because the square bracket character
[
has a special meaning in regular expressions. It is used to define a character class, which allows specifying a set of characters that can match at that position.In your example, the error is occurring because the regex pattern
Mat[
is not properly terminated. The closing square bracket]
is missing, causing the error message "Unterminated character class."To fix this issue, you need to escape the square bracket character using a backslash
to treat it as a literal character instead of a special character in the regular expression.