-3

I have a query string that I need to remove a certain parameter from. For instance, my query string may be "?name=John&page=12&mfgid=320", and I need to remove the "page" parameter from it and end up with "?name=John&mfgid=320". I cannot assume that the "page" parameter is or isn't followed by other parameters.

All my attempts at using JavaScript functions/regex are failing miserably, so I could really use a hand in getting this working. Thanks.

Jacob Stamm
  • 1,660
  • 1
  • 29
  • 53

2 Answers2

0

That's quite easy... It's just /page=\d+&?/

var uri = '?name=John&page=12&mfgid=320';
uri = uri.replace(/page=\d+&?/,'');
Reeno
  • 5,720
  • 11
  • 37
  • 50
0

You can use:

uri = uri.replace(/[?&]page=[^&\n]+$|([&?])page=[^&\n]+&/g, '$1');

RegEx Demo

We'll need to use alternation to cover all the cases of presence of query parameter. Check my demo for all test cases.

anubhava
  • 761,203
  • 64
  • 569
  • 643