正则表达式删除导致关键字的字符串的第一部分

时间:2014-10-08 14:32:12

标签: javascript regex

我觉得我有一个掌心向前的时刻,但我似乎无法让它发挥作用。

我有一条路径,我想删除它的开头到某个文件夹(它的不同文件夹,但文件夹的名称将始终相同)。

因此,对于 /path/to/templates/sometemplate.html ,我希望字符串只是 templates / sometemplate.html 。(已删除' /路径/到/&#39)。我不能分开' /'并删除前两个,因为另一个路径可能是 /yet/another/path/to/templates/sometemplate.html ....

顺便说一下,我在Grunt脚本中这样做,所以我正在查看Javascript string.replace()。

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:2)

你真的不需要正则表达式,只需使用String方法:

var s = '/yet/another/path/to/templates/sometemplate.html';
var r = s.substr(s.indexOf('/templates/') + 1)
//=> templates/sometemplate.html

答案 1 :(得分:1)

.*?(?=templates)

通过empty string尝试this.replace。请参阅演示。

http://regex101.com/r/hQ1rP0/81

相关问题