开发者

how do I capture something after something else? like a referer=someString

开发者 https://www.devze.com 2023-01-13 13:24 出处:网络
I have ref=Apple and my current regex is var regex = /ref=(.+)/; var ref = regex.exec(window.location.href);

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.


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);
    }
}


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

  • regular-expressions.info/Brackets for Capturing


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.


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)


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]);

0

精彩评论

暂无评论...
验证码 换一张
取 消