AppDividend
Latest Code Tutorials

Javascript Replace Example | Javascript String replace() Method

0

Javascript string replace() is an inbuilt function that is used to searches the string for a specified value or keyword, or a regular expression, and returns the new string where the specified values are replaced. The pattern can be a String or the RegExp, and the replacement can be the string or a function to be called for each match.

How to replace String in Javascript

  • Install Node.js if you have not because we are using Node.js and NPM to run the javascript examples.
  • Replace javascript using Javascript regular expressions.
  • Replace multiple occurrences of the substring in javascript.
  • Replace multiple words in the javascript string.
  • Replace spaces in a string.

Now let’s review each step in more detail.

Javascript replace()

Replacing text in a string is a general operation, and thank’s to the JS replace() method available on the String prototype, it’s effortless to do.

The syntax for the Javascript String replace() function is the following.

str.replace(regexp|substr, newSubstr|function)

Now let us take an example.

let myStr = 'Bill is the richest person alive';

console.log(myStr.replace('Bill', 'Jeff'));

The replace() method does not change a String object itself; it is called upon. It just returns a new string.

#Javascript String replace()

See the following code example.

// app.js

let myStr = 'Apple TV will be launching on 1st November 2019'; 
console.log(myStr.replace('Apple TV', 'Apple TV+'));

See the output.

➜  es git:(master) ✗ node app
Apple TV+ will be launching on 1st November 2019
➜  es git:(master) ✗

Javascript String replace method does not change the String object it is called on. It simply returns the new string.

To perform a global search and replace, including the g switch in the regular expression.

#Javascript replace regexp match

Matching an exact substring is good, but often we find ourselves needing to match a pattern instead. It can quickly be done by using the regular expression as the first argument.

// server.js

let myStr = 'we can do whatever we want, we are venom';
myStr = myStr.replace(/w/g, 'b');
console.log(myStr);

You can check it via the node server. Just go to the terminal and go to the root of the above server.js file and type the following command.

node server

See the output.

➜  es git:(master) ✗ node app
be can do bhatever be bant, be are venom
➜  es git:(master) ✗

#How to replace multiple occurrences of the substring in JavaScript

If we do not want to use the RegExp, then we can use the following technique to replace the substring with the multiple occurrences.

// server.js

let myStr = 'we can do whatever we want, we are venom';

String.prototype.replaceAll = function(search, replacement) {
  var target = this;
  return target.split(search).join(replacement);
};

console.log(myStr.replaceAll('w', 'b'));

So that is how we can replace the multiple occurrences. See the output.

➜  es git:(master) ✗ node app
be can do bhatever be bant, be are venom
➜  es git:(master) ✗

#Replace Array of Strings

Here is an example where we can iterate over an array of strings and replace the substrings.

let ingredients = ['Y-MEN', 'Avengers', 'Loki'];

ingredients = ingredients.map(ingredient => {
  return ingredient.replace('Avengers', 'Revengers');
});

console.log(ingredients); //[ 'Y-MEN', 'Revengers', 'Loki' ]

See the output.

➜  es git:(master) ✗ node app
[ 'Y-MEN', 'Revengers', 'Loki' ]
➜  es git:(master) ✗

#Specifying a string as a parameter

Javascript string replace can include the following particular replacement patterns:

Pattern Inserts
$$ Inserts a “$”.
$& Inserts a matched substring.
$` Inserts a portion of the string that precedes the matched substring.
$’ Inserts a portion of the string that follows the matched substring.
$n Where n is the positive integer less than 100, inserts the nth parenthesized the submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed.

#Specifying a function as a parameter

We can define the function as a second parameter. In this case, the function will be invoked after the match has been performed. The function returns a result, and that result will be used as the replacement string. On the replace() function, we can also pass the second argument as a function and not the plain string. Let us see how we can use that.

let myStr = '13 million possibilities has been seen by Doctor Strange';

myStr = myStr.replace(/\d+/, (match) => {
  return +match + 1;
});

console.log(myStr);

See the output.

➜  es git:(master) ✗ node app
14 million possibilities has been seen by Doctor Strange
➜  es git:(master) ✗

#Javascript replace multiple strings

If you want to replace multiple words in the string with multiple other words. You can use the javascript replace() function.

// app.js

let str = "Netflix has StrangerThings, BlackMirror, and HouseOfCards";
let mapObj = {
  StrangerThings:"Millie Bobby Brown",
  BlackMirror:"Anthony Mackie",
  HouseOfCards:"Kevin Spacey"
};
replacedString = str.replace(/StrangerThings|BlackMirror|HouseOfCards/gi, function(matched){
  return mapObj[matched];
});
console.log(replacedString);

See the output.

➜  es git:(master) ✗ node app
Netflix has Millie Bobby Brown, Anthony Mackie, and Kevin Spacey
➜  es git:(master) ✗

If you want to make a reusable code, then you can use the following code snippet.

// app.js

function replaceAll(str, mapObj){
  let result = new RegExp(Object.keys(mapObj).join("|"),"gi");

  return str.replace(result, function(matched){
      return mapObj[matched];
  });
}

let str = "Netflix has StrangerThings, BlackMirror, and HouseOfCards";
let mapObj = {
  StrangerThings:"Millie Bobby Brown",
  BlackMirror:"Anthony Mackie",
  HouseOfCards:"Kevin Spacey"
};
replacedString = replaceAll(str, mapObj);
console.log(replacedString);

So in the above code, you could pass the str and mapobj to a function, and it would return the transformed string.

It will give us the same output.

#Javascript replace all spaces

Let’s assume that I have a string that contains the multiple spaces. I want to replace these with a hash symbol. How can I replace all spaces?

Well, we can use the Javascript split(), and Javascript join() methods.

// app.js

let str = 'Millie Bobby Brown';
let replaced = str.split(' ').join('#');
console.log(replaced)

See the output.

➜  es git:(master) ✗ node app
Millie#Bobby#Brown
➜  es git:(master) ✗

Here one thing to note that the above solution is slower on large replacement compared to the reg expression version.

You can use the RegExp on the above code, like the following.

// app.js

let str = 'Millie Bobby Brown';
let replaced = str.replace(/\s/g, "#");
console.log(replaced)

You will get the same output.

#Conclusion

So in this Javascript String replace() method article, we have seen Javascript replace() function, Javascript replace regexp match, replace all string, replace characters of the string, replace all spaces with and without regexp.

Finally, Javascript Replace Example | Javascript String replace() Method is over. Thanks for taking it.

Recommended Posts

Javascript String indexOf Example

Javascript String valueOf Example

Javascript String charCodeAt() Example

Javascript String lastIndexOf Example

Javascript String ToUpperCase Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.