如何在URL中获取第一个查询字符串的值

时间:2014-02-18 03:44:12

标签: javascript

您好我使用以下代码在表单字段中获取查询字符串值:

<script>
var url = window.location.search;
url = url.replace("?Id=", ''); // remove the ? 
</script>
<script>document.write("<input name='Id' data-constraints='@Required(groups=[customer])' id='Id' type='text' value='"+url+"' />");</script>

如果我访问[这不是链接](http://mydomain.com/?Id=987),它会在字段中记录Id,但是当包含更多参数时,它还会在字段中记录,我只想要第一个或任何特定的查询字符串参数在表单字段中添加?

2 个答案:

答案 0 :(得分:2)

如何使用查询字符串参数构建一个漂亮的小关联数组,如:

var urlParams = [];
window.location.search.replace("?", "").split("&").forEach(function (e, i) {
    var p = e.split("=");
    urlParams[p[0]] = p[1];
});

// We have all the params now -> you can access it by name
console.log(urlParams["Id"]);

答案 1 :(得分:0)

基本上,您需要检查是否存在&符号,将子字符串添加到&符号。

您可以在执行替换后添加此代码:

var start = url.indexOf('&');

if(start > 0) {
    url = url.substring(0, start);
}