Reputation: 59
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
Reputation: 59
I found out that the lookbehind also works, like (?<=y).*$
will return a position after y
.
Upvotes: 1
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
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