This Regex works fine in Chrome and Firefox
let regexp = new RegExp(`^${searchTerm}|(?<=\\s)${searchTerm}`, 'gi')
but unfortunately Safari complains
SyntaxError: Invalid regular expression: invalid group specifier name
It looks like Safari doesn't support the lookbehind, but how can I transform it so I get the indices of the searchTerm without the whitespaces?
let regexp = new RegExp(`^${searchTerm}|(?<=\\s)${searchTerm}`, 'gi')
let matchIndices = [...string.matchAll(regexp)].map(match => match.index);
matchIndices.forEach(index => {
...
});
CodePudding user response:
You can use a regex like /(^|\s)word/gi
and if Group 1 does not match a whitespace, collect the match index, otherwise, match index 1 value:
let searchTerm = "foo"
let string = "foo fooo,foo"
let regexp = new RegExp(`(^|\\s)${searchTerm}`, 'gi')
var matchIndices = [], m;
while(m = regexp.exec(string)) {
if (m[1] === "") {
matchIndices.push(m.index)
} else {
matchIndices.push(m.index 1)
}
}
matchIndices.forEach(index => {
console.log(index)
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>