如何从URL中提取“搜索词”?

时间:2011-03-03 02:48:57

标签: javascript

如何从以下网址中提取“测试”?

http://www.example.com/index.php?q=test&=Go

我找到了一个提取路径的脚本(window.location.pathname),但我无法找到或弄清楚如何提取或拆分URL。

-ben

3 个答案:

答案 0 :(得分:4)

var m = window.location.search.match(/q=([^&]*)/);

if (m) { 
    alert(m[1]); // => alerts "test"
} 

答案 1 :(得分:1)

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的插件:

URL Parser JQuery

答案 2 :(得分:0)

如果您只想要第一个词的值,那么:

function getFirstSeachValue() {
  var s = window.location.search.split('&');
  return s[0].split('=')[1];
}

如果你想要'q'项的值,无论它在搜索字符串中的位置如何,那么以下内容将返回传递的term的值,如果该项不在搜索字符串中,则返回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
相关问题