以下正则表达式匹配URL中的最后一个单词:
var match = (location.search.match(/(w+)$/))
? location.search.match(/(w+)$/)[0]
: "";
问题是,有时URL看起来像这个www.mysite.com/match-last-word/
,所以word
不匹配,因为末尾有斜杠。
我试过这个:
var match = (location.search.match(/(w+)$/*/))
? location.search.match(/(w+)$/*/)[0]
: "";
但没用。
试试这个:
var match = (location.search.match(/(w+|w+/)$/))
? location.search.match(/(w+|w+/)$/))[0]
: "";
在最后添加模式W*
以匹配零个或多个非单词字符。
b(w+)W*$
或
bw+(?=W*$)
(?=W*$)
正向前瞻断言,该断言断言匹配w+
后面必须跟有W*
、零个或多个非字字符,并且后面还要跟有行尾。
示例:
> var s = "www.mysite.com/match-last-word/"
undefined
> s.match(/bw+(?=W*$)/)[0]
'word'
location.search
为您提供url的查询参数。如果url是example.com/whatever/?q=123&name=something
,那么location.search将在问号之后为您提供所有信息。然而,如果url类似于example.com/whatever/
,那么location.search根本不会给你任何信息。所以当你做location.search.match()
时,你在寻找一些不存在的东西。
如果您想可靠地找到路径名中的最后一个单词(例如.com/asdf/targetwood),请使用以下方法:location.pathname.match(/[^/]+($|(?=/$))/i)[0]
基本上,它在url路径中查找最后一组非斜杠字符。
如果它是连字符的,这也是有效的。例如,example.com/asdf/longer-title/
将为您提供longer-title
。
您试图在$
(在本例中表示主题结束)之后匹配,而您应该在之前匹配:
location.search.match(/(w+)/?$/)
我已经将匹配设置为可选,这样它就可以匹配带有或不带有尾部斜杠的匹配。查找匹配的单词:
location.search.match(/(w+)/?$/)[1];
示例:
> '?text=word/'.match(/(w+)/$/)
["word/", "word"]
您尝试的操作不起作用,因为$代表行的末尾,所以您不能有/AFTER。如果您通过将/*移动到$之前来更正它,它应该按照您尝试的方式工作:
var match = (location.search.match(/(w+)/*$/))
? location.search.match(/(w+)/*$/)[0]
: "";