Home > Enterprise >  How to regex replace a query string with matching 2 words?
How to regex replace a query string with matching 2 words?

Time:01-15

I have a url and I want to replace the query string. For example

www.test.com/is/images/383773?wid=200&hei=200

I want to match the wid= and hei= and the numbers don't have to be 200 to replace the whole thing so it should look like this.

Expected www.test.com/is/images/383773?@HT_dtImage

So I've tried doing but it only replaced the matching wei and hei.

const url = "www.test.com/is/images/383773?wid=200&hei=200"

url.replace(/(wid)(hei)_[^\&] /, "@HT_dtImage")

CodePudding user response:

I would just use string split here:

var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.split("?")[0]   "?@HT_dtImage";
console.log(output);

If you only want to target query strings havings both keys wid and hei, then use a regex approach:

var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.replace(/(.*)\?(?=.*\bwid=\d )(?=.*\bhei=\d ).*/, "$1?@HT_dtImage");
console.log(output);

CodePudding user response:

You can make use of lookaround using regex /\?.*/

enter image description here

const url = 'www.test.com/is/images/383773?wid=200&hei=200';

const result = url.replace(/\?.*/, '?@HT_dtImage');
console.log(result);

  •  Tags:  
  • Related