2012-02-26 29 views
2

我將我的網址與此查詢字符串:得到使用JavaScript和正則表達式

http://mysite.com/results.aspx?s=bcs&k=「醫院」或「辦公室」或「基金」

我想「K =」後搶的一切,但不包括' K =」本身..

而且此正則表達式是部分working..but它抓住具有k兩次一切..

<script type="text/javascript"> 
document.write('<p>Showing Results for all' + 
window.location.href.match(/[?&]k=([^&#]+)/) || [] + '</p>'); 
</script> 
+0

HTTPS://developer.mozilla .org/en/JavaScript/Reference/Global_Objects/String/match讀取關於返回值的部分。 – 2012-02-26 02:13:17

回答

1

match正在返回的兩個元素。第一個是整個正則表達式的匹配。第二個元素是捕獲組(在()內)。這就是你想要的,數組中的第二個元素。

<script type="text/javascript"> 
    var result = window.location.href.match(/[?&]k=([^&#]+)/); 

    var word = ""; 

    if(result) word = result[1]; 
</script> 

http://jsfiddle.net/7WcMc/

+0

我該如何抓住?使用javascript? – 2012-02-26 02:15:37

+0

更新的答案有一點更詳細。 – 2012-02-26 02:17:53

0

的Javascript匹配函數返回匹配的數組。

在你的情況的第一場比賽是整個字符串匹配,二是反向引用([^ &#] +)

這樣可能會更好:

<script type="text/javascript"> 
    var m = window.location.href.match(/[?&]k=([^&#]+)/); 
    document.write('<p>Showing Results for all' + ((m != null) ? m[1] : '') ++ '</p>'); 
</script> 
相關問題