Javascript 获取最后一个“之间的字符串”;斜杠;第一点是;问号;

Javascript 获取最后一个“之间的字符串”;斜杠;第一点是;问号;,javascript,Javascript,我有一个url,如下所示: http://google.com/foo/querty?act=potato http://google.com/foo/querty/?act=potato http://google.com/foo/querty/#/21312ads http://google.com/foo/querty#/1230982130asd 对于这种URL格式,如何在javascript中使用正则表达式仅获取“query”字符串?将URL与“?”匹配: 要将URL与“#”匹配,请

我有一个url,如下所示:

http://google.com/foo/querty?act=potato
http://google.com/foo/querty/?act=potato
http://google.com/foo/querty/#/21312ads
http://google.com/foo/querty#/1230982130asd
对于这种URL格式,如何在javascript中使用正则表达式仅获取“query”字符串?

将URL与“?”匹配:

要将URL与“#”匹配,请执行以下操作:

要使两者匹配:

str.match(/^.*\/([^\/]+)\/?[#\?].*$/)[1];
我建议:

var url = "http://google.com/foo/querty?act=potato".split('/').pop(),
    urlPart = url.slice(0,url.indexOf('?'));
    console.log(urlPart);
考虑到不必要的复杂性,我强烈建议不要为此使用正则表达式(但这当然是个人偏好)

编辑以解决上述问题中未能满足问题中显示的两个测试用例的问题(在第二个用例中失败)。以下内容处理指定的两种情况:

Object.prototype.lastStringBefore = function (char, delim) {
    if (!char) {
        return this;
    }
    else {
        delim = delim || '/';
        var str = this,
            index = str.indexOf(char),
            part = str.charAt(index - 1) == delim ? str.split(delim).slice(-2, -1) : str.split(delim).pop();
        return part.length === 1 ? part[0] : part.slice(0, part.indexOf(char));
    }
}

var url1 = 'http://google.com/foo/querty?act=potato',
    url2 = 'http://google.com/foo/querty/?act=potato',
    lastWord1 = url1.lastStringBefore('?', '/'),
    lastWord2 = url2.lastStringBefore('?', '/');

console.log(lastWord1, lastWord2);

参考资料:

用于查找
并提取部分字符串:

url.substr(url.lastIndexOf('?'));

当然,你是对的;编辑以纠正短消息。谢谢你的接球!谢谢你的回答,我用新的信息编辑了我的问题。不幸的是,如果我使用
www.foo.bar/123#/abc
正则表达式采用
abc
。如何将(#)添加到正则表达式中?对不起,我忘了输入新问题。我需要正则表达式也检查一下。。。比如:
www.google.com.br/foo/#/bar
我希望正则表达式只接受
foo
因为
bar
不是“真正的目录”。
Object.prototype.lastStringBefore = function (char, delim) {
    if (!char) {
        return this;
    }
    else {
        delim = delim || '/';
        var str = this,
            index = str.indexOf(char),
            part = str.charAt(index - 1) == delim ? str.split(delim).slice(-2, -1) : str.split(delim).pop();
        return part.length === 1 ? part[0] : part.slice(0, part.indexOf(char));
    }
}

var url1 = 'http://google.com/foo/querty?act=potato',
    url2 = 'http://google.com/foo/querty/?act=potato',
    lastWord1 = url1.lastStringBefore('?', '/'),
    lastWord2 = url2.lastStringBefore('?', '/');

console.log(lastWord1, lastWord2);
url.substr(url.lastIndexOf('?'));