31

I want to use the pattern *1*. I have tried \*1\*, but it doesn't work. Where is the problem?

Mike
  • 23,542
  • 14
  • 76
  • 87
user2080105
  • 1,642
  • 4
  • 18
  • 27

2 Answers2

36

You have to escape it with a backslash:

/\*1\*/

Otherwise, an unescaped * in a RegExp will mean: Match 0 or more of the Preceding Character Group.

Update:

If you use the RegExp constructor, do it this way:

new RegExp("\\*1\\*")

You have to double-escape the backslashes because they need to be escaped in the string itself.

Beat Richartz
  • 9,474
  • 1
  • 33
  • 50
  • i have edited my question, but yes i used backslash and it doesn't work – user2080105 Mar 04 '13 at 15:57
  • The forward slashes mark the start and the end of the regexp. You have to start with a forward slash and end with one, and in between escape the asterisks with backslashes. Exactly like in the example I've given. – Beat Richartz Mar 04 '13 at 15:58
  • no but i m using RegExp constructor so i don't need to use forward slash – user2080105 Mar 04 '13 at 15:59
  • @user2080105 I updated my question. If you construct a RegExp via a string, you'll have to double-escape. If you're using some other tool, please document it in your question. – Beat Richartz Mar 04 '13 at 16:03
  • @BeatRichartz you mean you updated your answer? – Adam Burley Jul 23 '21 at 14:20
0

need to use a backslash \ as the escape character in regexes.