
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Validate input: replace all ‘a’ with ‘@’ and ‘i’ with ‘!’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?
- Related Articles
- How not to validate HTML5 input with required attribute
- How can I replace newlines with spaces in JavaScript?
- How can I validate EditText input in Android?
- Capitalize a word and replace spaces with underscore - JavaScript?
- Replace All Elements Of ArrayList with with Java Collections
- MySQL: How can I find a value with special character and replace with NULL?
- How I can replace a JavaScript alert pop up with a fancy alert box?
- Replace commas with JavaScript Regex?
- How can I delete all cookies with JavaScript?
- Replace all words with another string with Java Regular Expressions
- Replace NaN with zero and infinity with large finite numbers for complex input values in Python
- How can I validate EditText input in Android using Kotlin?
- Replace a letter with its alphabet position JavaScript
- How to Replace null with “-” JavaScript
- Replace All Occurrences of a Python Substring with a New String?

Advertisements