1

I'm having trouble writing a regex that removes any of these parameters from a url using javascript:

pricerange=-#

pricerange=#-#

pricerange=#-

This works ok for all except the last one. It doesn't remove pricerange=40-

var postUrl = "http://www.test.com/directory/?cat=203604&pricerange=-10&pricerange=10-20&pricerange=20-30&pricerange=30-40&pricerange=40-" 

postUrl = postUrl.replace(/[&\?]\bpricerange\=[0-9]*-[0-9]*\b/g, ""); 

Result:

http://www.test.com/directory/?cat=203604&pricerange=40-

Expected result:

http://www.test.com/directory/?cat=203604

Here is the jsbin.

There could be other parameters in the url that I wouldn't want to remove.

2 Answers 2

5

Try it again after removing ending \b

online demo

OR use (\b|$) to match either word boundary or end of the line

Corrected online demo


Your regex will not work correctly if cat=203604 is some where in between pricerange query parameters.

for example:

http://www.test.com/directory/?pricerange=-10&cat=203604&pricerange=10-20&pricerange=20-30&pricerange=30-40&pricerange=40-

Output: (Query parameter should be started by ?)

http://www.test.com/directory/&cat=203604

You can correct it, using &*\bpricerange\=[0-9]*-[0-9]*&*

Here is online demo

Sign up to request clarification or add additional context in comments.

8 Comments

Specifically voting up the second version. Also, no need for the \b after the [&\?], so: /[&\?]pricerange\=[0-9]*-[0-9]*(\b|$)/g
Yes you are right. No need to use \b because [&\?] is already defined as prefix
@PaulRoub \b is needed. Look at the updated post. There is one more fault in OP regex patern.
I guess the only issue is if the url is this "test.com/directory/?pricerange=10-20" then the '?' stays there.
Sorry, still not there. This one doesn't work: test.com/directory/?pricerange=-10&pricerange=10-20
|
1

Does it have to be a regular expression? We're going through a lot of gymnastics to make that happen. A function would do the job:

function cleaner(url)
{
  var parts = url.split("?");

  if (parts.length == 2)
    {
      var comps = parts[1].split('&');

      for ( var i = comps.length - 1; i >= 0; --i )
        {
          if (comps[i].match(/^pricerange=\d*\-\d*$/))
            comps.splice(i, 1);
        }

      if (comps.length > 0)
        parts[1] = comps.join('&');
      else
        parts.splice(1, 1);
    }

  return parts.join("?");
}

var postUrl = "http://www.test.com/directory/?cat=203604&pricerange=-10&pricerange=10-20&pricerange=20-30&pricerange=30-40&pricerange=40-" 

postUrl = cleaner(postUrl);

Example: http://codepen.io/paulroub/pen/srfCj

1 Comment

Thank you. Also a good suggestion. Probably easier to maintain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.