[英]javascript - search(regex), get position of the last character of the matched string
In javascript, the String.search()
returns the position (character index) of the character at the start of the match when there are multiple characters . javascript中,当有多个字符时,
String.search()
返回匹配开始的字符的position(字符索引)。 Meaning, for example, if you try to regex search cde
in abcdefghij
, it returns 2
(where c
is at) and not 4
(where e
is at).意思是,例如,如果您尝试在
abcdefghij
中使用正则表达式搜索cde
,它会返回2
( c
所在的位置)而不是4
( e
所在的位置)。 How do I do this?我该怎么做呢? I wouldn't just take the position, add by a fixed number, and you'll get the last character (
Position + 2
), that won't work if the match have varying length match.我不会只取 position,加上一个固定的数字,你会得到最后一个字符 (
Position + 2
),如果匹配有不同的长度匹配,那将不起作用。
Use match
instead.改用
match
。 You can use a capture group to add the length of the match.您可以使用捕获组来添加匹配的长度。
const [, group, index] = "abcdfghij".match(/(cde?)/)
/* Make sure results are not undefined */
const lastIndex = index + (group.length - 1);
You could always create your own method.您始终可以创建自己的方法。
function indexLastCharacter(string, search_word) {
let indexFirstCharacter = string.search(search_word);
return indexFirstCharacter + search_word.length;
}
console.log(indexLastCharacter("abcdefghij", "cde"))
// -> 5
I found out that the lookbehind also works, like (?<=y).*$
will return a position after y
.我发现 lookbehind 也有效,例如
(?<=y).*$
将在y
之后返回 position。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.