Most Efficient Way to Find Last Occurrence of a Character in a Given Range

I’m fairly new to JavaScript and need to find an efficient way to get the index of the last occurrence of a space character within a given range. I’m not sure if this could be done with RegEx or not; I’m currently doing it with the built in string methods, however, building a new string with the substring method seems like a waste for what I need.

My current solution:

Let n be the end of the range

    let spaceIndex = stringText.substr(0, n + 1).lastIndexOf(" ");

Answer

Sure, just use the second argument to lastIndexOffromIndex:

let spaceIndex = stringText.lastIndexOf(" ", n + 1)

Leave a Reply

Your email address will not be published. Required fields are marked *