Defang an IP Address with JavaScript

I was asked this question long ago. At first, I was stumped. Not because the question is tricky, but because my brain shuts down when multiple people are stairing at the back of my head while I’m standing in front of a white board.

However, this question is quite easy. And the solution will probably jump out at you immediately. Although, if you’re like me, you may be stumped at first because of the panic attack you’re having in the interview room.

Why would we defang an IP address?

Well, first of all, when we’re dealing with text data that includes IP addresses (e.g. forums, chat applications, etc.), a common practice is to defang IP addresses to prevent them from being rendered as clickable links, preventing accidental navigation to sensitive locations.

Likewise, in some security-related contexts, such as logs, IPs may need to be obfuscated or defanged, protecting the privacy of individuals or to avoid exposing specific network infrastructure details.

Let’s explore the problem.

Defanging an IP Address

This interview question involves taking a standard IPv4 address, which is typically represented with periods (".") separating each segment, and modifying it by replacing those periods with a specific sequence of characters.

This modification is often required to prevent the IP address from being recognized as a hyperlink in certain contexts, such as in text fields or documents.

So an IP address such as 192.168.1.1 would be defanged to 192[.]168[.]1[.]1.

Did you think of a solution yet?

You might immediately be thinking of running through the string with a for loop, looking for periods, and so on. And that’s a valid solution. Heck, it might be the solution your interviewer is looking for, because the other way is extremely simple.

So let’s explore this iterative solution first.

function defangIPaddr(ip) {
    let defangedIP = '';

    for (let i = 0; i < ip.length; i++) {
        if (ip[i] === '.') {
            defangedIP += '[.]';
        }
        else {
            defangedIP += ip[i];
        }
    }

    return defangedIP;
}

console.log(defangIPaddr('192.168.1.1'));

There’s our iterative solution. Very simple, eh? Define a variable with an empty string value, loop through the string provided as input, setting the values into defangedIP. But there’s an even simpler way, which is how I solved this problem the first time.

If you’re familiar with Regular Expressions, you may already know what to do – make a call to our good friend .replace().

function defangIPaddr(address) {
    return address.replace(/\./g, '[.]');
}

console.log(defangIPaddr('192.168.1.1'));

Simple as that. The regular expression looks for a period and replaces it with '[.]', exactly what we want. Of course, this works with all sorts of questions which may be similar, so it’s worth remembering the solutions to this problem.

Update: Community Members Solutions

There are always numerous ways to solve a problem, and some readers of this article have suggested their own solutions.

Hri7566’s Solution:
const ip = '192.168.0.1';
console.log(ip.split(".").join("[.]"));
Matjah’s Solution:
const input = '192.168.0.1';
console.log(input.replaceAll(`.`, `[.]`));
// 192[.]168[.]0[.]

Conclusion

In this article, we explored two solutions to the defang an IP problem, offering an iterative solution as well as using a method and a regular expression.

Have you ever been asked this problem before? Have a better solution? Or a unique solution? Let us know down below in the comments.

comments powered by Disqus

Related Posts

Solving a Common Interview Question: the Two Sum Algorithm in JavaScript

Imagine you’re at a lively party, and everyone is carrying a specific number on their back. The host announces a game – find two people whose numbers add up to the magic number, and you win a prize!

Read more

Remove Duplicates from Arrays and Strings in JavaScript

Removing duplicates is a common problem in programming that can arise in various contexts, such as cleaning up data or ensuring unique entries.

Read more

Remote First: 5 Websites for Remote Job Opportunities

Would you prefer to work in an office, or while sitting at a beach somewhere in Thailand (i.e. remotely)? Okay, maybe there’s no beach in this scenario, but there’s definitely silence, and maybe your cat.

Read more