在JS中将字符串与regex进行比较

时间:2014-04-13 19:13:26

标签: javascript regex

我想将字符串与正则表达式进行比较。 例如:

return path == "/blog/2";

如何用正则表达式替换URL(数字)的最后一部分? 我希望第一部分(博客)和最后一部分的数字匹配完全匹配(例如:/ blog / 1,/ blog / 49,/ blog / 20913是可能的组合)。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你可以用

替换最后一部分
 path.replace(/(\/blog)\/\d+/, '$1/replacement value')

在行动中看到它&解释:http://regex101.com/r/vR1pB7

/(\/blog)\/\d+/
    1st Capturing group (\/blog)
        \/ matches the character / literally
        blog matches the characters blog literally (case sensitive)
    \/ matches the character / literally
    \d+ match a digit [0-9]
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]

答案 1 :(得分:0)

使用\d+[0-9]+作为数字:

/\/blog\/\d+/.test(path)

如果您想匹配整个字符串,请使用锚点^$

/^\/blog\/\d+$/.test(path)