How to replace string in JavaScript

How to replace string in JavaScript

1920 1080 mrrohit

In this post, we are going to learn about a different way to replace string.
As we know that string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with another string.

 

Only Replaces One

Syntax :

str.replace(A, B);

here A will be your string that you want to replace with B.

replace string
 
 var message = 'we love people and we love always';
var newMessage = message.replace('love', 'care');
console.log(newMessage);

Output: we care people and we love always

Here we expected that all the occurrences of love will replace with care. But it just replaces only the first occurrence. So how we can replace all the occurrences of a string? So let’s begin

Replaces All with literal regular expression

Normally String replace() only replaces the first instance it finds.
We’ll have to use a regular expression using /g.

replace all string
 
 var message = 'we love people and we love always';
var newMessage = message.replace(/love/g, 'care');
console.log(newMessage);

Output: we care people and we care always

Using RegExp()

Here, we can use the constructor function of the RegExp object. Using ‘g’

replace all string
 
var message = 'we love people and we love always';
var newMessage = message.replace(new RegExp('love', 'g'), 'care');
console.log(newMessage);

Output: we care people and we care always

Split and Join (Functional) Implementation

One more best way to replace string using split and join. So firstly you have to add given string in split() and replacing strings in a join().

replace all string
 
var message = 'we love people and we love always';
var newMessage = message.split('love').join('care');
console.log(newMessage);

Output: we care people and we care always

GitHub

https://github.com/talenteddeveloper/javascript/blob/master/stringReplace.js

Press Ctrl+C to copy the following code.
"