Get index of last occurence of matched string?

Viewed 112

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
3 Answers

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

Your solution is not efficient because this is go through every character text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1. You can simply using a for loop: Run and check the code below:

const text = "Hello, this is a test. foo"
const validChecker = [".",",",";"] // any char you want
const findLast = (text,validChecker) =>{
  if(!text) return
  for(let i = text.length -1; i>=0; i--){
    if(validChecker.includes(text[i])){
      return i
    }
  }
}

console.log(findLast(text,validChecker))

Related