正则表达式匹配的最后一个字符

时间:2016-07-08 14:26:20

标签: javascript regex

我正在尝试使用正则表达式来检测当前页面查询字符串中的模式。

出于这个原因,我有以下正则表达式:

var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");

我正在针对此输入进行测试:

http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd

它可以很好地找到模式。

我真正想要得到的是相对于整个网址的最后一个字符索引。

例如,如果我想要索引o最后一个' d'字符:

http://127.0.0.1:33822/?year=2015&country=Portugal&format=ps**d**

在这个特定情况下,我想要60。

提前致谢

1 个答案:

答案 0 :(得分:2)

您可以使用match.index。它将为您提供原始字符串中匹配的位置。 然后,您可以使用matche[0].length查找匹配中的最后一个字符

 key='format'
 re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");
 url='http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd'

match=url.match(re)

console.log(match.index + match[0].length-1) // 60