0

I'm using www.regexr.com to check my regular expressions in JavaScript. Let's assume I have the following string:

/facilityservices/show/1/price_min:sdc155sd/

Now my task is to find price_min:sdc155sd and remove it. I wrote

var patterns_array = [
    'price_min:\w+'
];

var pattern = new RegExp(patterns_array.join("|"), "g");
new_url = current_url.replace(pattern, '');

ON the website above this RegExp matches the word. However when I checking my website it doesn't work. Where I have an error. It's too easy to make mistake...

Pointy
  • 405,095
  • 59
  • 585
  • 614
VIPPER
  • 326
  • 4
  • 24

2 Answers2

0

Your pattern doesn't work because you're creating it from a string. In this case, that's not necessary:

var pattern = /price_min:\w+/;

will do it.

When you create a regular expression from a string, you have to deal with the fact that the string grammar also thinks backslash characters (\) are special. Thus, by the time the RegExp constructor sees your string to interpret it as a regular expression, the backslash before the "w" will be gone. If you need to create a regex from a string, you have to double the backslash characters:

var pattern = new RegExp("price_min:\\w+");

Again, in this particular case that's not necessary.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

This is because RegExp escapes \w (as normal string) you need \\w.

var patterns_array = [
    'price_min:\\w+'
];

From the docs:

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary

Also the above will work but you'll be left with two trailing slash // in your result you should instead apply this:

price_min:\\w+\/?
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64