-2

Can anyone help me with this regex I can't get the regex to match. I'm trying to remove the phrases that match from the string

let url = 'en-gb/products/product-category/186/product-type/2';
let word = "product-category";
let regex = new RegExp("\/" + word + "\/\d+", "g");
let output = url.replace(regex, '');
//desired output = 'en-gb/products/product-type/2'
console.log(output);
Jordan
  • 148
  • 7

1 Answers1

3

You were close, you need to do it like so:

let url = 'en-gb/products/product-category/186/product-type/2';
let word = 'product-category';
let regex = new RegExp(word + '/\\d+/', 'g');
let output = url.replace(regex, '');
//desired output = 'en-gb/products/product-type/2'
console.log(output);

Also please try to be consistent with either double or single quotes.

inorganik
  • 24,255
  • 17
  • 90
  • 114