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

Viewed 446

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.

3 Answers

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

I found out that the lookbehind also works, like (?<=y).*$ will return a position after y.

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
Related