繁体   English   中英

javascript - 搜索(正则表达式),获取匹配字符串最后一个字符的 position

[英]javascript - search(regex), get position of the last character of the matched string

javascript中,当有多个字符时String.search()返回匹配开始的字符的position(字符索引)。 意思是,例如,如果您尝试在abcdefghij中使用正则表达式搜索cde ,它会返回2c所在的位置)而不是4e所在的位置)。 我该怎么做呢? 我不会只取 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM