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
Validate input: replace all 'a' with '@' and 'i' with '!'JavaScript
We need to write a function validate() that takes a string as input and returns a new string where all occurrences of 'a' are replaced with '@' and all occurrences of 'i' are replaced with '!'.
This is a classic string manipulation problem that can be solved using different approaches. Let's explore the most common methods.
Using For Loop
The traditional approach iterates through each character and builds a new string:
const string = 'Hello, is it raining in Amsterdam?';
const validate = (str) => {
let validatedString = '';
for(let i = 0; i
Hello, !s !t r@!n!ng !n @msterd@m?
Using replace() Method
A more concise approach uses JavaScript's built-in replace() method with regular expressions:
const string = 'Hello, is it raining in Amsterdam?';
const validate = (str) => {
return str.replace(/a/g, '@').replace(/i/g, '!');
};
console.log(validate(string));
Hello, !s !t r@!n!ng !n @msterd@m?
Using split() and join()
Another approach splits the string and joins it back with replacements:
const string = 'Hello, is it raining in Amsterdam?';
const validate = (str) => {
return str.split('a').join('@').split('i').join('!');
};
console.log(validate(string));
Hello, !s !t r@!n!ng !n @msterd@m?
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | Good | Fast | Learning fundamentals |
| replace() | Excellent | Very Fast | Production code |
| split/join | Good | Slower | Simple replacements |
Handling Case Sensitivity
To handle both uppercase and lowercase letters, modify the regular expression:
const string = 'Alice is Amazing!';
const validate = (str) => {
return str.replace(/[aA]/g, '@').replace(/[iI]/g, '!');
};
console.log(validate(string));
@l!ce !s @m@z!ng!
Conclusion
The replace() method with regular expressions is the most efficient and readable approach for character replacement. Use the for loop method when you need more complex logic or want to understand the underlying process.
