[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 474
  • Last Modified:

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

0
adavir
Asked:
adavir
  • 2
  • 2
1 Solution
 
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
 
hieloCommented:
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
 
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

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now