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.

Updated on: 2026-03-15T23:18:59+05:30

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements