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

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more