2015-03-02 24 views
1

下面的正則表達式的最後一個字匹配在URL的末尾斜線:修改下面的正則表達式包含在URL

var match = (location.search.match(/(\w+)$/)) 
    ? location.search.match(/(\w+)$/)[0] 
    : ""; 

的問題是,有時網址看起來會像這樣www.mysite.com/match-last-word/所以word ISN沒有匹配,因爲最後有一個斜線。

我嘗試這樣做:

var match = (location.search.match(/(\w+)$\/*/)) 
    ? location.search.match(/(\w+)$\/*/)[0] 
    : ""; 

但沒有奏效。

+0

它可能不起作用,因爲'\/*'出現在錨,'$'後面。美元符號意味着字符串的結尾,所以在它之後放置任何東西都可能導致正則表達式以意想不到的方式行爲。 – ctt 2015-03-02 04:42:42

回答

1

在最後添加模式\W*以匹配零個或多個非單詞字符。

\b(\w+)\W*$ 

OR

\b\w+(?=\W*$) 

(?=\W*$)陽性預測先行斷言,它斷言匹配\w+必須後跟\W*,零個或多個非單詞字符和然後進一步通過線端。

例子:

> var s = "www.mysite.com/match-last-word/" 
undefined 
> s.match(/\b\w+(?=\W*$)/)[0] 
'word' 
+0

你是唯一一個工作,因爲另一個也匹配'/'。謝謝,你能簡單地解釋一下''='在那個正則表達式中做了什麼? – alexchenco 2015-03-02 06:05:41

+0

@alexchenco這是一個前瞻性斷言,這意味着匹配的執行不會成爲匹配本身的一部分;好處是你不需要記憶捕獲(就像在我的回答中一樣)。 – 2015-03-02 06:23:30

0

你試過沒有工作,因爲$代表行的末尾,這樣你就可以不用/後。如果您通過移動改正它的/ *到$之前,它應該工作你想它的方式:

var match = (location.search.match(/(\w+)\/*$/)) 
? location.search.match(/(\w+)\/*$/)[0] 
: ""; 
1

你試圖$(在這種情況下代表結束後,以匹配的東西的主題),而你應該匹配之前:

location.search.match(/(\w+)\/?$/) 

我已經使匹配可選,以便它匹配有或沒有結尾斜槓。要找到匹配的詞:

location.search.match(/(\w+)\/?$/)[1]; 

例子:

> '?text=word/'.match(/(\w+)\/$/) 
["word/", "word"] 
2

試試這個:

var match = (location.search.match(/(\w+|\w+\/)$/)) 
    ? location.search.match(/(\w+|\w+\/)$/))[0] 
    : ""; 
1

location.search給你一個網址的查詢參數。如果網址是example.com/whatever/?q=123&name=something,那麼location.search會在問號後爲您提供一切。但是,如果網址類似於example.com/whatever/,那麼location.search根本不會給你任何東西。所以當你做location.search.match(),你正在尋找一些不存在的東西。

如果你想找到可靠的路徑名(example.com/asdf/targetword)的最後一個字,然後使用此: location.pathname.match(/[^\/]+($|(?=\/$))/i)[0]

基本上,它看起來對最後一組非斜槓在一個url路徑中。

這也適用於連字符。例如,example.com/asdf/longer-title/會給你longer-title