AAsomb113
AAsomb113

Reputation: 59

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.

Upvotes: 3

Views: 1075

Answers (3)

AAsomb113
AAsomb113

Reputation: 59

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

Upvotes: 1

Edgar Marques
Edgar Marques

Reputation: 46

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

Upvotes: 1

OFRBG
OFRBG

Reputation: 1778

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

Upvotes: 1

Related Questions