Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Strings: Replacing i with 1 and o with 0
We are required to write a function that takes in a string as one and only argument and returns another string that has all 'i' and 'o' replaced with '1' and '0' respectively.
It's one of those classic for loop problems where we iterate over the string with its index and construct a new string as we move through.
Using For Loop
The most straightforward approach is to iterate through each character and build a new string:
const string = 'Hello, is it raining in Amsterdam?';
const replaceChars = (str) => {
let result = '';
for(let i = 0; i < str.length; i++){
if(str[i] === 'i'){
result += '1';
}else if(str[i] === 'o'){
result += '0';
}else{
result += str[i];
}
}
return result;
};
console.log(replaceChars(string));
Hell0, 1s 1t ra1n1ng 1n Amsterdam?
Using replace() Method
A more elegant solution uses the built-in replace() method with regular expressions:
const string = 'Hello, is it raining in Amsterdam?';
const replaceChars = (str) => {
return str.replace(/i/g, '1').replace(/o/g, '0');
};
console.log(replaceChars(string));
Hell0, 1s 1t ra1n1ng 1n Amsterdam?
Using split() and join()
Another approach uses split() and join() methods:
const string = 'Hello, is it raining in Amsterdam?';
const replaceChars = (str) => {
return str.split('i').join('1').split('o').join('0');
};
console.log(replaceChars(string));
Hell0, 1s 1t ra1n1ng 1n Amsterdam?
Comparison
| Method | Readability | Performance | Flexibility |
|---|---|---|---|
| For Loop | Good | Fast | High - easy to extend |
| replace() with regex | Excellent | Good | Medium |
| split() and join() | Good | Slower | Limited |
Conclusion
The replace() method with regular expressions provides the cleanest and most readable solution. Use the for loop approach when you need more complex character replacement logic.
