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

adavirAsked:
Who is Participating?
 
hieloConnect With a Mentor Commented:
but yes, you can use parenthesis to group in javascript:
<script type="text/javascript">
var str="http://www.somesite.com?name=john&age=90&height=3#main";
var regex = new RegExp("[\\?&](([^=]+)=([^&#]+))","g");
var result = []; 
while( str.match(regex) )
{
	result[result.length]=RegExp.$1;
	str = str.replace( RegExp.$1, "" );
}
alert( result );
</script>

Open in new window

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

0
 
adavirAuthor Commented:
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

0
 
adavirAuthor Commented:
sorry the alert would be "http, http, http",
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.