Link to home
Start Free TrialLog in
Avatar of adavir
adavir

asked on

Javascript Regular Expression Groups

Hi,

I was wondering if there was any way of using groups in Javascript regular expressions. I know it can be done on the server side but I am having trouble getting it going on the client side.

For instance in .NET I would do the following

Regex regex = new Regex("[?|&]?(?<key>[^=]+)=(?<value>[^&]+)");

This would give me 2 groups on a match ..."key" and "value".

All suggestions much appreciated.

Paul

Avatar of hielo
hielo
Flag of Wallis and Futuna image

are try to get the key/value pairs from a querystring? If so refer to:
http://blog.falafel.com/2007/12/17/ParseAQueryStringInJavaScript.aspx

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of adavir
adavir

ASKER

Good Job,

I was a bit baffled when I first read your code, I thought this can't be correct. What if there were concurrent RegExp instances. For instance if you look at the code attached the final alert would be "http"

Not a very OO way for Javascript to implement RegExp groups. But heh it works!

Thanks again, you obviously know your javascript

Paul
<script type="text/javascript">
var str="http://www.somesite.com?name=john&age=90&height=3#main";
var regex = new RegExp("[\\?&](([^=]+)=([^&#]+))","g");
var protocolRegex = new RegExp("(http|ftp|gopher)");
var result = []; 
while( str.match(regex) )
{
         var protocolMatch = str.match(protocolRegex);
 
	result[result.length]=RegExp.$1;
	str = str.replace( RegExp.$1, "" );
}
alert( result );
</script>

Open in new window

Avatar of adavir

ASKER

sorry the alert would be "http, http, http",