views:

66

answers:

5

I have ref=Apple and my current regex is

    var regex = /ref=(.+)/;
    var ref = regex.exec(window.location.href);
    alert(ref[0]);

but that includes the ref=

now, I also want to stop capturing characters if a & is at the end of the ref param. cause ref may not always be the last param in the url.

+2  A: 

Use ref[1] instead.

This accesses what is captured by group 1 in your pattern.

Note that there's almost certainly a better way to do key/value parsing in Javascript than regex.

References

polygenelubricants
ref[0] s a reference to the whole string that was searched. I also agree that parsing key value pairs are much smoother using String.split. Ext-JS has a method called urlDecode that turns urls into a key/value object. And can be used like var params=Ext.urlDecode(location.search); http://dev.sencha.com/deploy/dev/docs/source/Ext.html#method-Ext-urlDecode
Juan Mendes
+1  A: 

Capture only word characters and numbers:

var regex = /ref=(\w+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);

Capture word characters, numbers, - and _:

var regex = /ref=([\w_\-]+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);

More information about Regular Expressions (the basics)

Lekensteyn
`\w` already matches digits, so `[\w\d]` is redundant.
Alan Moore
Funny. I always forget about that, and I always discover it afterwards :p
Lekensteyn
+1  A: 

You are using the ref wrong, you should use ref[1] for the (.+), ref[0] is the whole match. If & is at the end, modify the regexp to /ref=([^&]+)/, to exclude &s. Also, make sure you urldecode (unescape in JavaScript) the match.

SHiNKiROU
+3  A: 

You'll want to split the url parameters, rather than using a regular expression.

Something like:

var get = window.location.href.split('?')[1];
var params = get.split('&');
for (p in params) {
    var key = params[p].split('=')[0];
    var value = params[p].split('=')[1];

    if (key == 'ref') {
        alert('ref is ' + value);
    }
}
Seth
A: 

try this regex pattern ref=(.*?)&

This pattern will match anything after ref= and stop before '&'

To get the value of m just use following code:

var regex = /ref=(.*?)&/;

var ref = regex.exec(window.location.href);

alert(ref[1]);