views:

28

answers:

2

What I want


From the above subject I want to get search=adam and page=content and message=2.

Subject:


/search=adam/page=content/message=2

What I have tried so far


(\/)+search+\=+(.*)\/ 

But this is not good because sometimes the subject ends with nothing and in my case there must be a /

(\/)+search+\=+(.*?)+(\/*?)

But this is not good because goes trought the (\/*?) and shows me everyting what's after /search=

Tool Tip:


Regex Tester

+3  A: 

Use String.split(), no regex required:

var A = '/search=adam/page=content/message=2'.split('/');

Note that you may have to discard the first array item using .slice(1).

Then you can iterate through the name-value pairs using something like:

for(var x = 0; x < A.length; x++) {
    var nameValue = A[x].split('=');
    if(nameValue[0] == 'search') {
        // do something with nameValue[1]
    }
}

This assumes that no equals signs will be in the value. Hopefully this is the case, but if not, you could use nameValue.slice(1).join('=') instead of nameValue[1];

idealmachine
+2  A: 

shows me everyting what's after /search=

You used a greedy .* that will happily match slashes as well. You can use a non-greedy .*?, or a character class that excludes the slash:

(\/|^)search=([^\/]*)(\/|$)

Here the front and end may be either a slash or the start/end (^/$) of the string. (I removed the +s, as I can't work out at all what they're supposed to be doing.)

Alternatively, forget the regex:

var params= {};
var pieces= subject.split('/');
for (var i= pieces.length; i-->0;) {
    var ix= pieces[i].indexOf('=');
    if (ix!==-1)
        params[pieces[i].slice(0, ix)]= pieces[i].slice(ix+1);
}

Now you can just say params.search, params.page etc.

bobince