Languages

JavaScript - RegExp sticky, lastIndex and String replace() doesn't work together under Apple Safari

8 points
Asked by:
elmer
646

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
Answered by:
elmer
646

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join