0

I am having some trouble parsing one part of the following URL out:

http://port-80.********************************************.box.************.com/********/search/?sid=123875&brands=DELL|KROCKS&sort=popularity

I am trying to parse out the following: DELL|KROCKS.

So far I have the following regex expression which works to a certain extent:

/brands=(.*)[\&?]/

What the above does is if the & character is after the brands, it will get the following: DELL|KROCKS. However, if the & is not there, it will get the following: DELL|KROCKS&sort=popularity.

Is there any way I can fix this?

4
  • 1
    Why not just match [^&?]* instead of (.*)[\&?]? Commented Nov 10, 2014 at 21:33
  • How, if "the & is not there", can it "get the following: DELL|KROCKS&sort=popularity"? Commented Nov 10, 2014 at 21:34
  • Have you tried using any URL parsing libraries to break the query portion down into useful parts? Commented Nov 10, 2014 at 21:36
  • This worked: [^&?]* ! Thank you very much! brands=([^&?]*) Commented Nov 10, 2014 at 21:38

2 Answers 2

1

Use a generic URL parser.

Like this: How to get the value from URL Parameter?

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");

    var params = {}, tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}
var query = getQueryParams("http://port-80.********************************************.box.************.com/********/search/?sid=123875&brands=DELL|KROCKS&sort=popularity");
alert(query.brands);
Sign up to request clarification or add additional context in comments.

Comments

0

I did it like this brands=(.*?)(?:&|$)

This is a great tool for testing regex with groups https://www.debuggex.com/r/WgYVhtG4Zrn4f5gH

Comments

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.