[英]javascript - search(regex), get position of the last character of the matched string
javascript中,当有多个字符时, String.search()
返回匹配开始的字符的position(字符索引)。 意思是,例如,如果您尝试在abcdefghij
中使用正则表达式搜索cde
,它会返回2
( c
所在的位置)而不是4
( e
所在的位置)。 我该怎么做呢? 我不会只取 position,加上一个固定的数字,你会得到最后一个字符 ( 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
我发现 lookbehind 也有效,例如(?<=y).*$
将在y
之后返回 position。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.