Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert this Regex with lookbehind so it works in Safari?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 => {
   ...
});

>Solution :

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)
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading