0

I am writing some regex to my app. But I got some problem to rewrite regex from https://regexr.com to javascript code. In regexer my regex works fine. But in JS it does not.

I am aware that, I have to escape some special characters in regex, but in this case I misunderstand something.

val.toString().match("^\+?(\(\d{2,4}\))?(?!.*([ -])\\2)[0-9- ]*$") !== null;
zolty13
  • 1,943
  • 3
  • 17
  • 34
  • The issue is due to the fact the `+` is at the start of a regex. If you use a RegExp constructor (here, implicitly) double the backslashes. Else, use a regex literal if you are not passing any variables to the regex. `val.toString().match(/^\+?(\(\d{2,4}\))?(?!.*([ -])\2)[0-9- ]*$/)`. – Wiktor Stribiżew Jun 04 '19 at 07:53
  • It should match phone number with prefix. Optional + and (country code). I would like also to prevent double spaces and -. Thank you it works fine. I was not aware of this mechanism. Write and answer accept – zolty13 Jun 04 '19 at 07:56
  • Regex literal works fine, but I am not able to write regex constuctor: ^\\+?(\\(\d{2,4}\\))?(?!.*([ -])\\2)[0-9- ]*$" – zolty13 Jun 04 '19 at 08:03
  • Why are you unable to do that? `new RegExp("^\\+?(\(\d{2,4}\))?(?!.*([ -])\\2)[0-9- ]*$")` works for me. EDIT: although you probably want `new RegExp("^\\+?(\\(\\d{2,4}\\))?(?!.*([ -])\\\\2)[0-9- ]*$")` – VLAZ Jun 04 '19 at 08:04
  • *Double the backslashes*: `val.toString().match("^\\+?(\\(\\d{2,4}\\))?(?!.*([ -])\\2)[0-9- ]*$")` – Wiktor Stribiżew Jun 04 '19 at 08:06
  • See [Why do regex constructors need to be double escaped?](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) – Wiktor Stribiżew Jun 04 '19 at 08:07
  • thank you for patience. Now I've got it – zolty13 Jun 04 '19 at 08:10

0 Answers0