Skip to content
Advertisement

JavaScript: Search string from position

JavaScript has two useful methods, both which nearly do what I need.

  • String.prototype.indexOf() will search for a substring and return its position. It has an optional position parameter which is the starting point of the search, so you can easily find the next one.
  • String.prototype.search() will search a string using a regular expression and return its position. However, as far as I can tell, it doesn’t allow a starting position, so it always searches from the start.

Is there anything which allows me to find the position using a regular expression which does allow for a starting position?

Advertisement

Answer

You could do a String#slice in advance to get rid of unwanted parts and then take String#search.

function search(string, regexp, from = 0) {
    const index = string.slice(from).search(regexp);
    return index === -1
        ? -1
        : index + from;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement