-2

If the '[' special character is used in a 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 is this error occurring and how can I solve this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Web Dev
  • 1
  • 2

2 Answers2

0

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:

/Mat\[/

You'll also need to escape the backslash itself to convert from the string to a regular expression. Thus, your code should be:

var text = "Mat\\[";
phatfingers
  • 9,770
  • 3
  • 30
  • 44
  • incorrect, that will produce the same error. You are just escaping that character in the string, it will not be escaped in the reg exp. – epascarello Jun 22 '23 at 16:06
  • What is the correct to escape this – Web Dev Jun 22 '23 at 16:09
  • An oversight on my part. Corrected. – phatfingers Jun 22 '23 at 16:14
  • @WebDev — backslash is an escape in Javascript, so javascript sees "Mat\[" and makes the string "Mat[" ... the open-bracket was escaped. Now you pass that "Mat[" to `new RegExp(...)` and the regex _doesn't_ see a backslash, JS took it out when it created the String object. So regex sees `Mat[` and `[` is special, and it's missing a closing bracket `]`. To get the backslash to RegExp you have to escape the escape: `var text = "Mat\\["`. I see phatfingers corrected that while I was writing this, but thought a fuller explanation might be helpful. – Stephen P Jun 22 '23 at 16:17
-2

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.

user3783243
  • 5,368
  • 5
  • 22
  • 41
Houssem TRABELSI
  • 782
  • 1
  • 5
  • 11