In this post, we are going to learn Javascript strings. replace() with examples we will replace first or all the occurrence of the substring in a given string by using regular expression.
JavaScript String.replace()
To replace a first occurrence or all occurrence of text in the string, we use the string.replace() method .It returns the new string after replacement with the given newSubstring by using string or regular expression.
Syntax with Regexp
string.replace(regexp, newSubstr| replacerFunction)
Parameters
- RegExp:- RegExp is an object or literal that matches all the occurrence of old string in given String and replaces them with newSubstr.
- newSubstr: This is string by which all occurrence we are looking by using RegExp in given string will be replaced. .we can use either string or function to create the newSubstr.
JavaScript String.replace() Syntax with substr
string.replace(substr, newSubstr|replacerFunction)
Parameters
- Substr:- The substring that we are looking in given String and replaces them with newSubstr.
- newSubstr: This is string by which first occurrence in given string will be replaced.we can use either use function or string to create newSubstr.
Return Value
It always returns a new string after replacement and does not make any change in the original string
1. Find First occurrence of string and Replace
The string first occurrence in the given string is replaced by a new subString not all. Let us understand with an example:
- The given String is ” The Moon rises and Moon Set and Moonlight good for health'”
- The substr we are looking in original string is “Moon”
- The new substring we have to replace is = ‘Sun’
In the below example, the substr we are looking for is ‘Moon’ and its first occurrence is replaced with newSubstr “Sun” in the given string as we can see in the output.The disadvantage is that only first occurrence is replaced. To replace all occurrences we can use regular expressions.
JavaScript Example to replace a string
let strsun = 'The Moon rises and Moon set and Moon light good for health';
console.log(strsun.replace('Moon' ,'Sun'));
Output
"The Sun rises and Moon set and Moon light good for health"
2. RegExp To find and replace all occurrence
If we want to replace all the occurrences of text from the original string we must use the RegExp for replacing. The ‘g’ is global flag searches and replaces all the occurrences of text in a given string. We often use ‘i’ which means ignore case.
Let us understand with an example
- Main string = ‘The Moon rises and Moon set and MOON light good for health’;
- Regexp = /Moon/gi;
- newSubstr = ‘Sun’
Here in this example, all occurrences of ‘Moon’ will get replaced with ‘Sun’.Because we have used Regular Expression(RegExp)
JavaScript Example to replace a string
let strsun = 'The Moon rises and Moon set and MOON light good for health';
const regexp = /Moon/gi;
console.log(strsun.replace(regexp ,'Sun'));
Output
"The Sun rises and Sun set and Sun light good for health"
3. Generate substr Using function
The function is called when a match is found. It will run for every match found in the string if we specify the (/g) in a regular expression. It is also known as a reducer.
Syntax
function replacer(match, p1, p2,..pn, offset, string)
{
//
}
function Parameters
- match : It represent the matched substring.
- p1, p2,..pn: We use these arguments if we need to get the nth group capture from the match.
- offset:The integer index position of the the match string.
- string:the string on which we are examining.
Let us understand with an example:
JavaScript Example to replace a string
let mystring = 'dev.com75693#$*%.';
newstr = mystring.replace(/([^\d]*)(\d*)([^\w]*)/, (match, p1, p2, p3, mystring) => {
return `${p1}---${p2}---${p3}`;
});
console.log(newstr);
Output
dev.com---75693---#$*%.
1. str.replace() to Switch the words
In this example we are switching the word Using string.replace() with two replacement patterns $1,$2.
What is $1,$2 to $9 in replace() JavaScript function
$1…….$9 are the static and read-only properties of the regular expression. It holds the string that matches with the parenthesis substing. To use them We use RegExp with the property. It stores RegExp global objects not individual RegExp objects.Let us understand with example
let regexp = /(\w+)\s(\w+)\s(\w+)/;
let switchstring = 'Group Tata The';
let newstr = switchstring.replace(regexp, '$3 $2 $1 ');
//Use the $1-$3property with RegExp global object
console.log(RegExp.$3);
console.log(RegExp.$2);
console.log(RegExp.$1);
console.log(newstr);
Output
"The"
"Tata"
"Group"
"The Tata Group "
2. How to use Variable in str.replace()
Some time in programming we need to replace all occurrences of a variable from a substring.Let us understand with example how we can do this:
JavaScript Program Example
var substr = "googlegamgam.com";
var regExpObj= new RegExp("gam","g");
var newstr = substr.replace(regExpObj,"");
console.log(newstr);
Output
google.com