正则表达式从URL捕获Google搜索词

时间:2015-09-05 16:03:26

标签: javascript regex

考虑以下网址(这是在Firefox中进行Google搜索的结果,然后通过Google界面更改搜索字词,从而添加以#开头的部分):

https://www.google.de/search?q=initial+search+term&ie=utf-8&oe=utf-8&gws_rd=cr&ei=Zw_rVfjrMMj8abKsn0g#q=changed+search+terms

我如何编写一个RegExp(JavaScript)来捕获"changed+search+terms",如果它存在于URL中,但默认为“initial + search + terms”?

此外,它应足够灵活,以支持不同的顶级域名,并接受网址中不同位置的"q=search+terms"部分。

到目前为止我已经

^https?://([^.]+\.)?google\.([a-z]+\.?)+/[^?/]*\?(.*&)?q=([^&]+)

但我似乎无法弄清楚如果存在第二个"q="如何。

1 个答案:

答案 0 :(得分:0)

您可以使用replace来查找值(如果存在)。这将削减你的正则表达式的额外检查,所以你需要做的就是搜索URL的?q =或#q =部分。

var found = ""

var s = "https://www.google.de/search?q=initial+search+term&ie=utf-8&oe=utf-8&gws_rd=cr&ei=Zw_rVfjrMMj8abKsn0g#q=changed+search+terms"

s.replace(/\?q=([^&#]+)|#q=([^&]+)/, function(m,a,b){
  found = (typeof a === "undefined") ? b : a;
});

console.log(found)