Regex Lookbehind Not Supported In Safari - How To Achieve The Same?
I am using the following regext (?<=')[^']+(?=')|\w{3,}/g. However I noticed it's not working in safari: https://caniuse.com/js-regexp-lookbehind How can I achieve the same that
Solution 1:
Use capture groups:
functionwords(s) {
var regex = /"([^"]+)"|(\w{3,})/g;
var result = [];
while (true) {
var match = regex.exec(s);
if (!match) break;
result.push(match[match[1] ? 1 : 2]);
}
return result;
}
console.log(words('xyz I am in the United States'));
console.log(words('xyz I am "in the United States"'));
The above solution could be done easier with .matchAll
and destructuring, but I suppose I shouldn't take the risk to use newer features, since you have no support for look behind.
Alternatively, you can use replace
, but actually throw away the main effect of it, and just use the side effect:
functionwords(s) {
var result = [];
s.replace(/"([^"]+)"|(\w{3,})/g, (_, quoted, word) =>
result.push(quoted || word)
);
return result;
}
console.log(words('xyz I am in the United States'));
console.log(words('xyz I am "in the United States"'));
Post a Comment for "Regex Lookbehind Not Supported In Safari - How To Achieve The Same?"