正则表达式从 JavaScript 中的 url 哈希中提取参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10624762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:29:50  来源:igfitidea点击:

RegEx to extract parameters from url hash in JavaScript

javascriptregexhash

提问by Gavriel

My urls will look like:

我的网址将如下所示:

http://example.com/whatever#page?x=1&locale=hu&y=2
http://example.com/whatever#page?x=1&locale=hu
http://example.com/whatever#page?locale=hu
http://example.com/whatever#page?locale=
http://example.com/whatever#page?x=1
http://example.com/whatever#page
http://example.com/whatever

I'd like to get the locale parameter or empty string if it's not set.

如果未设置,我想获取语言环境参数或空字符串。

I'm trying something like:

我正在尝试类似的东西:

locale = location.hash.replace(/.*(?:[?&]locale=([^&]*))?.*/, "");

But my problem is that I couldn't find the right RegExp that works for all cases (both when there's locale= in the hash and when there isn't)

但我的问题是我找不到适用于所有情况的正确 RegExp(无论是在哈希中有 locale= 时还是没有时)

回答by jfriend00

Here's a piece of code that will extract it from the hash and avoid it anywhere else in the URL:

这是一段代码,它将从散列中提取它并避免在 URL 的任何其他地方使用它:

function getLocaleFromHash(url) {
    var match = url.match(/#.*[?&]locale=([^&]+)(&|$)/);
    return(match ? match[1] : "");
}

And, you can see it work on all your test cases here: http://jsfiddle.net/jfriend00/p37Mx/

而且,您可以在这里看到它适用于所有测试用例:http: //jsfiddle.net/jfriend00/p37Mx/



If you want to be able to look for any parm in the hash, you would use this:

如果您希望能够在散列中查找任何参数,您可以使用以下命令:

function getParmFromHash(url, parm) {
    var re = new RegExp("#.*[?&]" + parm + "=([^&]+)(&|$)");
    var match = url.match(re);
    return(match ? match[1] : "");
}

See it work here: http://jsfiddle.net/jfriend00/6kgUk/

在这里看到它的工作:http: //jsfiddle.net/jfriend00/6kgUk/



A more generic function that will fetch all parameters in the URL would look like this. For normal URLs where the hash is after the query and the parameters are in the query string, it would look like this. This is a bit more code because it does more. It fetches all the parameters into an object where you can look up any parameter by it's key and it URL decodes them all too:

将获取 URL 中所有参数的更通用的函数如下所示。对于散列在查询之后且参数在查询字符串中的普通 URL,它看起来像这样。这是更多的代码,因为它做的更多。它将所有参数提取到一个对象中,您可以在该对象中通过它的键查找任何参数,并且它也对它们进行 URL 解码:

function getParmsFromURL(url) {
    var parms = {}, pieces, parts, i;
    var hash = url.lastIndexOf("#");
    if (hash !== -1) {
        // remove hash value
        url = url.slice(0, hash);
    }
    var question = url.lastIndexOf("?");
    if (question !== -1) {
        url = url.slice(question + 1);
        pieces = url.split("&");
        for (i = 0; i < pieces.length; i++) {
            parts = pieces[i].split("=");
            if (parts.length < 2) {
                parts.push("");
            }
            parms[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
        }
    }
    return parms;
}

For a special version that handles parameters in a hash value and after a ? in the hash value like in the OP's question (which isn't the typical case), one could use this:

对于处理散列值中和 ? 之后的参数的特殊版本。在 OP 问题中的哈希值中(这不是典型情况),可以使用以下方法:

function getParmsFromURLHash(url) {
    var parms = {}, pieces, parts, i;
    var hash = url.lastIndexOf("#");
    if (hash !== -1) {
        // isolate just the hash value
        url = url.slice(hash + 1);
    }
    var question = url.indexOf("?");
    if (question !== -1) {
        url = url.slice(question + 1);
        pieces = url.split("&");
        for (i = 0; i < pieces.length; i++) {
            parts = pieces[i].split("=");
            if (parts.length < 2) {
                parts.push("");
            }
            parms[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
        }
    }
    return parms;
}

Working demo: http://jsfiddle.net/jfriend00/v8cd5/

工作演示:http: //jsfiddle.net/jfriend00/v8cd5/

And, then if you wanted the local option, you'd just do this:

然后,如果您想要本地选项,您只需执行以下操作:

var parms = getParmsFromURL(url);
var locale = parms["locale"];

回答by soimon

locale = location.hash.match( /[?&]locale=([^&]*)?/ );
locale = ( locale == null ? "" : locale[1] || "" );

Will do the trick. I don't think the .*are needed, because you do not specify a start or an end of the string. I tested this regular expression on all your examples and they all worked correctly :)

会做的伎俩。我认为.*不需要,因为您没有指定字符串的开头或结尾。我在你所有的例子上测试了这个正则表达式,它们都正常工作:)

Edit:sorry, it was invalid in some cases. It is now correct in all cases.

编辑:抱歉,在某些情况下无效。现在在所有情况下都是正确的。

回答by twamley

If you really want to do it in one regex:

如果你真的想在一个正则表达式中做到这一点:

locale = location.hash.match(/([?&]locale=|^((?![?&]locale=).)+$)([^&]*)/)[3];

It works against all of your examples, though I imagine it's horribly inefficient.

它适用于您的所有示例,但我认为它的效率非常低。