2015-03-02 70 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