如何從下面的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