简体   繁体   中英

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 . 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). 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.

Use match instead. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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