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 optionalposition
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
.
JavaScript
x
7
1
function search(string, regexp, from = 0) {
2
const index = string.slice(from).search(regexp);
3
return index === -1
4
? -1
5
: index + from;
6
}
7