javascript 使用正则表达式获取 url 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5237725/
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-25 16:28:51  来源:igfitidea点击:

Take a url variable with regex

javascriptregex

提问by Patrique

I have the following url

我有以下网址

http://www.test.info/link/?url=http://www.site2.com

How do I get the value of the url parameter with regular expressions in javascript?

如何在javascript中使用正则表达式获取url参数的值?

Thanks

谢谢

回答by Andrew Mackrodt

function extractUrlValue(key, url)
{
    if (typeof(url) === 'undefined')
        url = window.location.href;
    var match = url.match('[?&]' + key + '=([^&]+)');
    return match ? match[1] : null;
}

If you're trying to match 'url' from a page the visitor is currently on you would use the method like this:

如果您尝试从访问者当前所在的页面匹配“url”,您可以使用如下方法:

var value = extractUrlValue('url');

Otherwise you can pass a custom url, e.g.

否则,您可以传递自定义网址,例如

var value = extractUrlValue('url', 'http://www.test.info/link/?url=http://www.site2.com

回答by Jordan

Check out http://rubular.comto test regex:

查看http://rubular.com来测试正则表达式:

url.match(/url=([^&]+)/)[1]

回答by amosrivera

Might want to check this: http://snipplr.com/view/799/get-url-variables/(works without regEx)

可能想检查一下:http: //snipplr.com/view/799/get-url-variables/(无需正则表达式即可工作)

This one does use regEx: http://www.netlobo.com/url_query_string_javascript.html

这个确实使用正则表达式:http: //www.netlobo.com/url_query_string_javascript.html

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


var param = gup( 'var' );

回答by Srdjan Pejic

Well, firstly, is that the whole query string? If so, all you need to do is split on the =:

那么,首先,这是整个查询字符串吗?如果是这样,您需要做的就是在 = 上拆分:

url.split('=')[1];

Otherwise, you might want to use Jordan's Regex.

否则,您可能想使用 Jordan 的 Regex。

回答by Vasyl Zubach

On the answer code:

在答案代码上:

function extractUrlValue(key, url)
{
    if (typeof(url) === 'undefined')
        url = window.location.href;
    var match = url.match('[?&]' + key + '=([^&#]+)');
    return match ? match[1] : null;
}

If keyis a last parameter in URL and after that there is an anchor - it enter code herewill return value#anchoras a value. #in regexp '[?&]' + key + '=([^&#]+)'will prevent that.

如果key是 URL 中的最后一个参数,然后有一个锚点 - 它在此处输入代码将value#anchor作为值返回。#在正则表达式中'[?&]' + key + '=([^&#]+)'会阻止这种情况。