从URL查询字符串中获取特定值

4
我有以下URL,想要使用JavaScript获取其中的"id"值。
https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go
我开始使用以下代码:
var url = document.URL;
var id_check = /^\id...\E; // NOT SURE HERE
var final_id = new RegExp(id_check,url);

我想提取id "B0077RQGX4" 并将其保存到变量中,以便稍后修改。我该如何在JavaScript中做到这一点,需要使用哪些函数?

6个回答

17

我想到了这个:

var final_id;
var url = document.URL;
var id_check = /[?&]id=([^&]+)/i;
var match = id_check.exec(url);
if (match != null) {
    final_id = match[1];
} else {
    final_id = "";
}

适用于:

https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?SomethingElse=Something&id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?commit=go&id=B0077RQGX4
final_id = 'B0077RQGX4'

https://www.blabla.com/ebookedit?commit=Go
final_id = ''

https://www.blabla.com/ebookedit?id=1234&Something=1&id=B0077RQGX4&commit=Go
final_id = '1234'

当使用这种方法时,如果 id 在查询字符串中出现超过一次会发生什么? - TLS
它将返回第一个 id 值。 - Adri V.

4

虽然您可以使用Regex来实现这一点,但如果使用非正则表达式方法很可能会更容易或更一致。事实上,这是因为查询字符串的布局可能有各种各样的排列方式(id值在首、尾或中间)。

编辑:@AdrianaVillafañe证明可以轻松地使用Regex完成此操作! 我将保留此仅限于JavaScript的方法,因为它确实有效。

我喜欢使用这个JavaScript方法来解析URL中的查询字符串并获取与所需名称匹配的第一个值。 在您的情况下,“id”将是name参数。

// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
    if (query.indexOf("?") == 0) { query = query.substr(1); }
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split("=");
        if (pair[0] == name) {
            return pair[1];
        }
    }
    return "";
}

要使用此方法,您需要传递URL中的查询字符串部分和您想要获取的值的名称。如果您想解析当前请求的URL,则可以执行以下操作:

var value = GetQueryVariable(location.search, "id");

尝试在正则表达式中实现这一点很可能会不一致,尤其是当处理查询字符串布局的可能变化时。

正则表达式非常有趣!但你的方法绝对更安全。+1 - kafuchau
我曾经尝试过(很多月前)设计一个单一的正则表达式来执行此操作,但最终我得出结论,这个多行JS函数会更加一致(并且实际上可以工作!)。请确保接受最佳答案以帮助您解决问题。 - TLS
如果有需要的话,您可以做类似的事情,但很容易返回一个具有所有数据作为属性和值对的对象。在&上分割,然后在= 上进行拆分循环即可。 - qw3n
@qw3n - 我实际上有一个单独的方法,返回整个名称/值对,而不仅仅是值。你说得对,让它返回所有匹配的名称/值对也不会太困难。 - TLS

1

只需尝试此操作。

function getUrlVars()
{
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value)   
  {
     vars[key] = value;
  });
  return vars;
} 


function urlval()
{
    var x=getUrlVars()["id"];
    alert (x);
 }

现在,x将会给id赋值为B0077RQGX4。

0
以下代码非常有效,比我找到的大多数解决方案都更易于理解。
<script>
//Pulls the variables from a URL and saves them
function $_GET(q,s) {
    s = (s) ? s : window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}

//Get the variables value
var urlvariablevalue = $_GET('id');

//Display the Value of the id from the URL
document.write(urlvariablevalue);
</script>

0

虽然它不是正则表达式,但你可以这样做

id=url.split('id=')[1].split('&')[0];

1
假设 id 参数总是第一个参数。 - kafuchau

0

类似这样的代码应该可以运行。

var url = document.URL;
var regex = new RegExp("id=(.+)&");

var id = url.match(regex)[1];​​​​​​

示例 jsfiddle 在这里


1
假设“id”不是查询字符串中的最后一个条目。 - TLS
没错,Adriana的正则表达式更好。 - kafuchau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接