修改以下正则表达式以在URL的末尾包含斜杠

时间:2015-03-02 04:35:14

标签: javascript regex

以下正则表达式匹配网址中的最后一个字:

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

问题是,有时网址会显示为www.mysite.com/match-last-word/,因此word不匹配,因为最后有一个斜杠。

我试过了:

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

但没有工作。

5 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:1)

在最后添加模式\W*以匹配零个或多个非单词字符。

\b(\w+)\W*$

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

(?=\W*$)肯定的前瞻性断言,断言匹配\w+必须后跟\W*,零个或多个非单词字符,然后是行尾。

示例:

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

答案 2 :(得分:1)

你试图在 $之后匹配(在这种情况下代表主题的结尾),而你应该在之前匹配:

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

我已将匹配设置为可选,以便匹配或不匹配斜杠。要找到匹配的单词:

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

示例:

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

答案 3 :(得分: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

答案 4 :(得分:0)

你尝试过的东西没有用,因为$代表了行的END,所以你不能拥有/ AFTER它。如果你通过在$之前移动/ *来纠正它,它应该按你尝试的方式工作:

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