Search code examples
javascriptregexlookbehind

javascript regex look behind to replace a character


I have a long strings of code that look something like

hs2^Ȁ_^HELLO_x_fs2^Ȁ_^WORLD_x_gn3^Ȁ_^HOME_x_gs3^Ȁ…

I need to do a replace. A hex character is used repeatedly Ȁ and there’s always a ^ in front of it. I need to change the number that appears before each ^Ȁ Reduce those numbers by 1. So the final result will be…

hs1^Ȁ_^HELLO_x_fs1^Ȁ_^WORLD_x_gn2^Ȁ_^HOME_x_gs2^Ȁ…

I’m really only dealing with two numbers here, 2 or 3, so the code would read something like this…

If (any number directly before ^Ȁ ==2) change it to 1 else if (any number directly before ^Ȁ ==3) change it to 2

I’ve heard of something called a “lookback” or “look behind” is that what’s needed here?


Solution

  • You can use replace with a callback function, which will be used to replace each occurrence using your own logic:

    var str = "hs2^Ȁ_^HELLO_x_fs2^Ȁ_^WORLD_x_gn3^Ȁ_^HOME_x_gs3^Ȁ";
    var res = str.replace(/\d(?=\^Ȁ)/g, num => --num);
    
    console.log(res);

    In the regex above, you'll notice this: (?=...). It's a positive lookahead, as suggested by @revo. It allows you to match ^Ȁ, but avoid passing it to your callback function. Only the digit (\d) will be passed, and thus, replaced.