Defanging an IP Address

(#1108), Easy

Category: String

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

Brute Force – Manual Character Iteration

  • Initialize an empty string `result`.
  • Loop through each character in the given IP address.
  • If the character is a '.', append '[.]' to the result.
  • Otherwise, append the character itself.
  • Return the final `result` string.
var defangIPaddr = function(address) {
  let result = "";
  for (let char of address) {
    if (char === ".") {
      result += "[.]";
    } else {
      result += char;
    }
  }
  return result;
};

Optimized – Using replaceAll()

  • Use JavaScript’s built-in `replaceAll()` method.
  • Call `address.replaceAll('.', '[.]')` to directly replace all dots.
  • Return the result.
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