0

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>

7
  • Is there supposed to be another : before 1111? Commented Nov 8, 2024 at 22:44
  • No, I've updated now to reflect why it's deliberately like this. Commented Nov 8, 2024 at 22:47
  • of course, even a correct regex will also need to find the longest repeated sequence of :0000: - e.g. 1234:0000:0000:5678:0000:0000:0000:1234 would not become 1234::5678::1234 nor 1234::5678:0000:0000:0000:1234 ... it would be 1234:0000:0000:5678::1234 - so, since you need to find the longest sequence of 0000's, you'll probably end up with code that won't need to use regular expressions anyway Commented Nov 8, 2024 at 23:13
  • 1
    ^^ I am assuming you are dealing with "compressing" IPv6 addresses Commented Nov 8, 2024 at 23:21
  • What's the expected result if your string starts with the pattern like?0000:0000:2A00..., is it ::2A000... Commented Nov 9, 2024 at 6:22

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.