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?
CodePudding user response:
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;
}
CodePudding user response:
In order to get the position of the original position of the search result you could use Nina Scholz' approach and then re-add the characters removed from the start. For Instance:
const str = "Hello World!";
let start = 5;
const output = str.substring(start).search(/World/g) start;
console.log(output); //6
Note: Be careful with cases where .search()
returns -1
.
CodePudding user response:
The other answer is the way to go as its much clearer what the intention is, but if you had to use a regular expression, you could do it like this:
// This string should not include characters that have special
// meaning in regular expressions / should be escaped.
const inputString = "foo bar baz bar";
const offset = 8;
const searchString = "bar";
inputString.search(new RegExp(`(?=.{${offset})${searchString}`));
// (?= make sure ${searchString} ("bar")
// is preceded by:
// . anything
// {$(a number)} at least this many times:
// {8} in this example.
// The (?=A)B positive lookahead won't be included in the result,
// so you don't need to plus or minus the offset from the result:
// Example:
const str = 'aabbcc aabbcc aabbcc';
^ ^ ^
2 9 16
str.search(new RegExp(`(?<=.{${0}})bb`));
// Return 2
str.search(new RegExp(`(?<=.{${4}})bb`));
// Returns 9
str.search(new RegExp(`(?<=.{${10}})bb`));
// Returns 16
str.search(new RegExp(`(?<=.{${1000}})bb`));
// Returns -1
str.search(new RegExp(`(?<=.{${10}})doesntexist`));
// Returns -1