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?

camrymps
  • 327
  • 3
  • 11

2 Answers2

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);
Community
  • 1
  • 1
KrisWebDev
  • 9,342
  • 4
  • 39
  • 59
0

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

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

clueless_user
  • 131
  • 1
  • 1
  • 8