Search code examples
javascriptregexregex-lookaroundsnegative-lookbehind

What is lookbehind support in JS? How to replace it?


I have a string and I want to replace every 'i' that is NOT following/followed by any other i and replace it with 'z`. I know that there is negative lookahead and lookbehind.

Results shoud be:

i => z
iki => zkz
iiki => iikz
ii => ii
iii => iii

I tried to use this:

/(?<!i)i(?!i)/gi

and it failed and thrown an error: Invalid regex group.

Yet

/i(?!i)/gi

works fine, but matches second "i" in this: "ii".

Is there some other way?

What is support for lookbehind in JS if there is any?


Solution

  • In your case you don't really need look-behind:

    'iiki'.replace(/i+/g, (m0) => m0.length > 1 ? m0 : 'z')
    

    You can just use a function as the replacement part and test the length of the matched string.

    Here are all your test cases:

    function test(input, expect) {
      const result = input.replace(/i+/g, (m0) => m0.length > 1 ? m0 : 'z');
      console.log(input + " => " + result + " // " + (result === expect ? "Good" : "ERROR"));
    }
    
    test('i', 'z');
    test('iki', 'zkz');
    test('iiki', 'iikz');
    test('ii', 'ii');
    test('iii', 'iii');