JavaScript string replace() method | Replace string part

JavaScript has an in-built string.replace() method that is used to replace part of any given string with another string or a regular expression. Here, we just have to pass a value and the part of the string which will be replaced with that value.

At the very first, let’s start with an example:

var str = "I love red T-shirt.";
var new_str = str.replace("red", "blue");
console.log(new_str); // I love blue T-shirt.

In the above JavaScript code, we have taken a string. Using the replace() method we have replaced the “red” into “blue”. In the output, we are able to see “blue” instead of red.

Now see another example where we have two instances value which is “red”:

var str = "I love red T-shirt. My favorite color is red.";
var new_str = str.replace("red", "blue");
console.log(new_str); // I love blue T-shirt. My favorite color is red.

In the above code, we can see that only the first instance of our string part or value has been changed. But the other instance remains unchanged. It still has the value “red”. So, our method actually changes only the first value or string part.

To learn how to replace all the available instances values or parts of the given string in JavaScript, continue reading this article…

 

Global replacement of string part with string replace() method

See the example below which will replace all the instances available in the string:

var str = "I love red T-shirt. My favorite color is red.";
var new_str = str.replace(/red/g, "blue");
console.log(new_str); // I love blue T-shirt. My favorite color is blue.

Now we can see all of the instances in the string has been replaced with our value.

Till now, all of the ways of using the replace() method change our value in a case-sensitive way. For example, if we want to replace “red” with blue, then it will not be able to replace “Red”. To learn how to replace string part with case-insensitive way, continue reading this article.

 

Global, case-insensitive replacement in JavaScript string replace()

See the code below:

var str = "I love red T-shirt. Red is my favorite color.";
var new_str = str.replace(/red/gi, "blue");
console.log(new_str); // I love blue T-shirt. blue is my favorite color.

Also, read:

The above code will replace all the string parts in a case-insensitive way. In this example, “red” and “Red” both have replaced with “blue”.

 

So, in this article, we have learned how to replace the first part of given string, replacing all the instances both in case-sensitive and case-insensitive ways.

 

Leave a Reply

Your email address will not be published. Required fields are marked *