Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of last occurence of matched string?

Tags:

javascript

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
like image 416
Dan Avatar asked Sep 16 '25 23:09

Dan


2 Answers

let text = 'Hello, this is a test. foo'; 
let lastChar = [...text.matchAll(/[\.,;]/g)].pop().index
console.log(lastChar)
like image 112
symlink Avatar answered Sep 19 '25 14:09

symlink


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]);
like image 37
Aplet123 Avatar answered Sep 19 '25 15:09

Aplet123