如何从下面的URL中提取“测试”?如何从网址中提取“搜索字词”?
http://www.example.com/index.php?q=test&=Go
我已经找到了一个脚本来提取路径(window.location.pathname),但我无法找到或弄清楚如何提取或分割的URL。
-ben
如何从下面的URL中提取“测试”?如何从网址中提取“搜索字词”?
http://www.example.com/index.php?q=test&=Go
我已经找到了一个脚本来提取路径(window.location.pathname),但我无法找到或弄清楚如何提取或分割的URL。
-ben
var myURL = 'http://www.example.com/index.php?q=test&=Go';
function gup(name) //stands for get url param
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(myURL);
if(results == null)
return "";
else
return results[1];
}
var my_param = gup('q');
这里是jsfiddle
或者你也可以使用jQuery的插件:
对于此功能的改进版本,请参阅http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery/5158301#5158301 – James 2011-03-03 02:54:28
如果你只是想在第一项的值,那么:
function getFirstSeachValue() {
var s = window.location.search.split('&');
return s[0].split('=')[1];
}
如果您希望'q'项的值(不管它在搜索字符串中的位置),则以下内容将返回传递的项的值,如果该项不在搜索字符串中,则返回null:
function getSearchValue(value) {
var a = window.location.search.replace(/^\?/,'').split('&');
var re = new RegExp('^' + value + '=');
var i = a.length;
while (i--) {
if (re.test(a[i])) return a[i].split('=')[1];
}
return null;
}
这两个都只是一些例子,应该一路测试结果以防止出现意外错误。
--
Rob
我相信这个问题[解析JavaScript中的查询字符串](http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript)有解决方案。 – Justin 2011-03-03 02:53:28