Regular Expression help

Have a string, for example: “foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3”

But only want to extract certain parts of the string, such as foo1 and it’s value (until the semicolon), and foo3 and it’s value (until the semicolon).

Any idea’s how to do this? Have tried [foo1|foo3].*; but this might be nowhere near the solution…

var s=“foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3”;

You can match everything that starts with foo1 or foo3 and an equals sign,
plus everything til you hit a semicolon (or run out of characters).

alert(s.match(/\b(foo[13]=[^;]+)+/g));

/* returned value: (Array)
foo1=somevalue1,foo3=anothervalue3
*/

You could use something like the popular “getUrlParam” method, but slightly modified to your case. This would work well especially if your values are arbitrary but you know which you want to extract.


function getParam(name, from){
    var results = new RegExp('[\\\\?;]' + name + '=([^;#]*)').exec(from);
    if (!results) { return undefined; }
    return results[1] || undefined;
}

You can then call it like:


var paramString = "foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3";

var foo2 = getParam("foo2", paramString);