0

我在堆栈溢出中搜索了一个 Javascript 解决方案(在 jQuery 库中)以获取 URL 参数。

我有这个功能可以顺利完成:

// get the firstname value from the myurl - http://mysite.com?firstname=dany&lastname=dughy

var myurl = $("#gup").data("url");
var name = "firstname";

function gup(name, myurl) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec(myurl);
    if( results == null )
        return "";
    else
        return results[1];
}

我了解它的工作原理,您设置了一个正则表达式,然后执行该正则表达式并在数组中检索结果。

有人可以向我解释一下正则表达式吗?我似乎无法理解。

4

2 回答 2

2

Let's call the function with gup("NAME","http://domain.com?NAME=value&name2=value2").

function gup(name, myurl) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

This line escapes square brakets so it works nicely in the regex query, making "[]" into "\\\[\\\]".

    var regexS = "[\\?&]"+name+"=([^&#]*)";

Now the name is parsed to work in the regex. It will look like "[\\?&]NAME=([^&#]*)".

"[\\?&]" means find either ? or &. Because ? is a special character, to match a ? in text you need to escape it like \?, so this regex would become [\?&] but in javascript strings you need to escape the \ again. So [\?&] becomes "[\\?&]" in a string.

=([^&#]*) matches a literal = followed by any character except an & or #.

    var regex = new RegExp( regexS );
    var results = regex.exec(myurl);
    if( results == null )
        return "";
    else
        return results[1];

Returns the captured group, which is at position 1. Position 0 is the whole match.

}

Function call returns value

于 2013-02-05T13:02:58.047 回答
0

假设您正在搜索名字,那么正则表达式变为:[\\?&]firstname=([^&#]*)。现在,它的意思是:[\\?&]搜索任何 characters \?或者&之后有的firstname=,and [^&#]*= 除了&or#之后的任何字符

于 2013-02-05T12:36:44.333 回答