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"
Input: "255.100.50.0"
Output: "255[.]100[.]50[.]0"
๐ง 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.