How to use Regular Expression to replace characters from String In Javascript
To replace all occurrences of a string in JavaScript using a regular expression, we can use the regular expression with the global (g
) Flag.
Example: In this example we will replace “Welcome” with “Hello” in the given string “Welcome w3wiki, Welcome geeks”.
const str = 'Welcome w3wiki, Welcome geeks';
const searchString ="Welcome";
const replacementString ="Hello";
let regex = new RegExp(searchString, 'g');
let replacedString =
str.replace(regex, replacementString);
console.log(replacedString);
Output
Hello w3wiki, Hello 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