search(regex),获取匹配字符串的最后一个字符的位置



在javascript中,当有多个字符时,String.search()返回字符在匹配开始时的位置(字符索引(。这意味着,例如,如果您尝试在abcdefghij中正则表达式搜索cde,它将返回2(其中c位于(,而不是4(其中e位于(。我该怎么做?我不会只取这个位置,加上一个固定的数字,你就会得到最后一个字符(Position + 2(,如果匹配的长度不同,这就不起作用。

请改用match。您可以使用捕获组来添加匹配的长度。

const [, group, index] = "abcdfghij".match(/(cde?)/)
/* Make sure results are not undefined */
const lastIndex = index + (group.length - 1);

您可以始终创建自己的方法。

function indexLastCharacter(string, search_word) {
let indexFirstCharacter = string.search(search_word);
return indexFirstCharacter + search_word.length;
}
console.log(indexLastCharacter("abcdefghij", "cde"))
// -> 5

我发现lookbacking也能工作,就像(?<=y).*$会在y之后返回一个位置一样。

最新更新