EN
JavaScript - RegExp sticky, lastIndex and String replace() doesn't work together under Apple Safari
1
answers
8
points
I have noticed, when I use sticky flag in RegExp object with String replace() method, RegExp lastIndex property doesnt work. Is it normal behaving that in Applie Safari from 2020 it doesn't work and in Google Chome it works? How to solve the problem?
This code shows my problem (run it in the Applie Safari and Google Chome):
// ONLINE-RUNNER:browser;
const text = 'abcd';
const expression = /bc/y; // <----- sticky flag
expression.lastIndex = 1;
console.log(text.replace(expression, '__'));
Result I get under Apple Safari:
abcd
Result I get under Google Chome:
a__d
1 answer
1
points
In the both web borwsers it should be working the same way.
To solve the problem you can use the custom implementation of replace() method: https://dirask.com/snippets/JavaScript-example-RegExp-prototype-replace-method-implementation-pJZm7p
e.g.
// ONLINE-RUNNER:browser;
const replaceText = (expression, text, replacer) => {
if (typeof replacer === 'string') {
const tmp = replacer;
replacer = () => tmp;
}
const global = expression.global;
let index = 0;
let result = '';
while (true) {
const match = expression.exec(text);
if (match === null) {
break;
}
const entry = match[0];
result += text.substring(index, match.index);
result += replacer(...match);
index = match.index + entry.length;
if (global === false) {
break;
}
}
result += text.substring(index, text.length);
return result;
};
// Usage example:
const text = 'abcd';
const expression = /bc/y; // <----- sticky flag
const replacer = 'BC';
expression.lastIndex = 1;
console.log(replaceText(expression, text, replacer)); // OR: replaceText(expression, text, (match) => replacer)
0 comments
Add comment