How to use split and join Method to Replace Characters from a String In Javascript
In this approach, the split method is used to divide the string into an array of substrings based on the substring we want to replace. Then, the join method is used to combine the array back into a string, with the new substring replacing the old one.
Example: Here we will replace “GfG” with “Geeks” in the given string “Welcome to GfG”.
const str = 'Welcome to GfG';
const oldStr = 'GfG';
const newStr = 'Geeks';
const updatedStr = str.split(oldStr).join(newStr);
console.log(updatedStr);
Output
Welcome to Geeks
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