javascriptregex-replace

How to regex replace a repeated sequence?


For example, if there a sequence of 2 or more :0000: then I like to replace them with :.

In the code below, the result should be 2a00:1450:4028:805::00001111:2005 but it just ignores the replacement.

BTW, if it's just a single :0000: then it should be replaced with :0:, but this should be fairly easy once the real issue is solved. Note I've deliberately used 00001111 to make sure it doesn't get replaced.

let str = document.getElementById("input").textContent; 
let res = str.replace(/(:0000:){2,}/g, ":");
document.getElementById("output").textContent = res;
Before:
<p id="input">
2A00:1450:4028:080B:0000:0000:00001111:2005
</p>
After
<p id="output">
</p>


Solution

  • The problem is that your pattern /(:0000:){2,} requires that each 0000 be separated by ::, not just :, e.g. :0000::0000::0000:. You should have : at the beginning or end of the group, not both. Then you can match another : outside the quantified group.

    And if you want :: in the result, you should use that in the replacement, not just :.

    let str = document.getElementById("input").textContent; 
    let res = str.replace(/(:0000){2,}:/g, "::");
    document.getElementById("output").textContent = res;
    Before:
    <p id="input">
    2A00:1450:4028:080B:0000:0000:00001111:2005
    </p>
    After
    <p id="output">
    </p>