I want to get the index of the last occurrence of a character in a string which is part of a match string. What's the most efficient way to do this?
Something like match(/[\.,;]/g)
but I want the index in the original string of the last element of the returned array, the way that match(/[\.,;]/)
gives the index of the first match.
E.g., if string is Hello, this is a test. foo
I want the index of the last period/comma/semicolon.
The best solution I've come up with is reversing the string and finding first match:
text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1
let text = 'Hello, this is a test. foo';
let lastChar = [...text.matchAll(/[\.,;]/g)].pop().index
console.log(lastChar)
A bit of a hacky solution, but you can use a function as an argument to replace:
const matches = [];
const text = "foo.bar,qaz";
// don't use any capturing groups otherwise the function will be messed up
text.replace(/[\.,;]/g, (match, offset) => matches.push(offset));
console.log(matches[matches.length - 1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With