How to use map() & split() method to replace characters from String In Javascript
In this approach, split(‘ ‘) is used to split the string into an array of words. Then, map() is used to iterate over each word in the array. If the word is equal to oldWord, it is replaced with newWord; otherwise, the word remains unchanged. Finally, join(‘ ‘) is used to join the array back into a string
Example: Here we will split the given string “Hello user, welcome to w3wiki” and replace the “Hello” with “Hi”.
const str = "Hello user, welcome to w3wiki";
oldWord='Hello';
newWord='Hi'
const replacedString=str.split(' ').map(word => word === oldWord ? newWord : word).join(' ');
console.log(replacedString);
Output
Hi user, welcome to w3wiki
JavaScript Program to Replace Characters of a String
Given a String the task is to replace characters of String with a given String in JavaScript.
Examples:
Input: Str = Welcome to GfG
strRepl = GfG
newStr = Geeks
Output: Welcome to Geeks
Table of Content
- Using map() & split() method to replace characters from String
- Using String replace() Method to replace characters from String
- Using Regular Expression to replace characters from String
- Using split and join Method to Replace Characters from a String
Contact Us