Defanging an IP Address(#1108)

Category: String, Foundation

๐Ÿงฉ Problem Statement

Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every '.' with '[.]' to avoid accidental linking or execution in web contexts.

๐Ÿ“š Examples

Input: "1.1.1.1"

Output: "1[.]1[.]1[.]1"

Explanation: Each '.' is replaced with '[.]', so the result becomes '1[.]1[.]1[.]1'.

Input: "255.100.50.0"

Output: "255[.]100[.]50[.]0"

Explanation: All '.' characters in the IP are replaced with '[.]'.

๐Ÿง  Approach

We can solve this problem in two ways.

Approach 1 โ€“ Brute Force:**

Loop through each character of the input string. If it's a '.', append '[.]' to the result string; otherwise, append the character itself.

Approach 2 โ€“ Optimized using replaceAll():**

Use JavaScript's built-in `replaceAll()` method to directly replace all occurrences of '.' with '[.]'. This is a clean, one-liner solution.

๐Ÿ’ป Code

// Approach 1: Brute Force
var defangIPaddr = function(address) {
  let result = "";
  for (let char of address) {
    if (char === ".") {
      result += "[.]";
    } else {
      result += char;
    }
  }
  return result;
};

// Approach 2: Using replaceAll()
var defangIPaddr = function(address) {
  return address.replaceAll(".", "[.]");
};

๐Ÿ“ˆ Complexity

Time: O(n), where n is the length of the input string.

Space: O(n), for the new string being returned.

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources