
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate Input: Replace All 'a' With 'i' Using JavaScript
We are required to write a function validate() that takes in a string as one and only argument and returns another string that has all ‘a’ and ‘i’ replaced with ‘@’ and ‘!’ 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.
The code for the function will be −
Example
const string = 'Hello, is it raining in Amsterdam?'; const validate = (str) => { let validatedString = ''; for(let i = 0; i < str.length; i++){ if(str[i] === 'a'){ validatedString += '@'; }else if(str[i] === 'i'){ validatedString += '!'; }else{ validatedString += str[i]; }; }; return validatedString; }; console.log(validate(string));
Output
The output in the console will be −
Hello, !s !t r@!n!ng !n Amsterd@m?
Advertisements