AppDividend
Latest Code Tutorials

Javascript Replace Example | Javascript String replace() Method

0

Javascript String replace() is an inbuilt function that 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 method to be called for each match.

How to replace String in Javascript

  1. Install Node.js if you have not because we are using Node.js and NPM to run the javascript examples.
  2. Replacing string using Javascript regular expressions.
  3. Replacing multiple occurrences of the substring in javascript.
  4. Replacing multiple words in the javascript string.
  5. Replacing spaces in a string.

Javascript String replace()

Javascript replace() method does not change the calling String object. It simply returns a new string. To perform a global search and replace, including the g switch in the regular expression. Replacing text in a string is a general operation and effortless operation.

Syntax

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

string.replace(searchvalue, newvalue)

Parameters

The replace() function takes two parameters.

The searchvalue is a required parameter, and it is the value or regular expression that will be replaced by the new value.

The newvalue is a required parameter, and it is the value to replace the search value with.

Return Value

The replace() method returns the new string, with some or all matches of a pattern replaced by a replacement.

Example

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.

See another 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) ✗

Specifying a function as a parameter

You can specify a method as the second parameter. In this case, the method will be invoked after the match has been performed. The function’s result (return value) will be used as the replacement string. See the below code.

const replacer = (match, a1, a2, a3, offset, string) => {
  return [a1, a2, a3].join(' - ');
}

let newString = 'ABC112119$*%#'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);

Output

ABC - 112119 - $*%#

In this example, we have differentiated three types of values with a hyphen and then join the string. Those three types of values are non-digits, non-alphabet, and special characters.

You can see that we have defined a replace() function as a second parameter which will be invoked after the match is performed. We have completely transformed the original string using string replace() and join() method.

One thing to note here that the method will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

Switching words in a string

To switch a text in Javascript, we can use replace() method because the script uses the capturing groups and the $1 and $2 replacement patterns.

let re = /(\w+)\s(\w+)/;
let str = 'Magnus Carlsen';
let newstr = str.replace(re, '$2, $1');
console.log(newstr);

Output

Carlsen, Magnus

You can see that we have switched the string from Magnus Carlen to Carlen, Magnus.

Replacing multiple occurrences 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.

// app.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) ✗

Replacing an Array of Strings in Javascript

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:

PatternInserts
$$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.
$nWhere n is the positive integer less than 100, inserts the nth parenthesized the submatch string, provided the first argument was a regex 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) ✗

Replacing multiple strings in Javascript

If you want to replace multiple words in the string with numerous 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.

Replacing 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 with regex match, replace an array of strings and all string, replace characters of the string, replace all spaces with and without regexp.

Finally, Javascript String replace() example is over. Thanks for taking it.

Recommended Posts

Javascript String indexOf()

Javascript String valueOf()

Javascript String charCodeAt()

Javascript String lastIndexOf()

Javascript String ToUpperCase()

Leave A Reply

Your email address will not be published.

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