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
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>[^=]+)
This would give me 2 groups on a match ..."key" and "value".
All suggestions much appreciated.
Paul
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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>
ASKER
sorry the alert would be "http, http, http",
http://blog.falafel.com/2007/12/17/ParseAQueryStringInJavaScript.aspx