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(" ");
Advertisement
Answer
Sure, just use the second argument to lastIndexOf
— fromIndex
:
let spaceIndex = stringText.lastIndexOf(" ", n + 1)