How to Replace a String or Substring in JavaScript?

Are you ready to discover how to replace a string or substring in JavaScript? Read on!

In this article, you’ll learn about the powerful replace() method, understand its syntax and parameters, and see practical examples of how it can be used in different scenarios.

So, without further ado, let’s dive into practical examples and learn how to manipulate strings like a pro.

What is replace() method in JavaScript?

The replace() method in JavaScript is used to return a new string with some or all matches of a pattern replaced by a replacement.

It can be a string or a RegExp (regular expression) and you can use a word or a special function to decide what the new parts will be.

In other words, The replace() method allows you to substitute a part of a string with something else.

This “something else” could be a different string or the result of a function.

Syntax

string.replace(searchValue, newValue)

Parameters

searchValue (Required)

It’s the value or regular expression to search for.

newValue (Required)

It is the new value you want to replace with.

Return value

A new string, with some or all matches of a pattern replaced by a replacement.

Here’s an example:

let oldsamplestring = "Welcome to Amazingworld!";
let newsamplestring = oldsamplestring.replace("Amazingworld", "Itsourcecode"); ✅
console.log(newsamplestring);  

Output:

Welcome to Itsourcecode!

📌Keep in mind that the replace() method doesn’t modify the original sentence. If you need to switch out all occurrences of a word, you’ll need to use a regular expression with the ‘g’ modifier.

How to use replace() method to replace a String or Substring in JavaScript?

Here’s how you can use the replace() method in JavaScript to replace a string or substring:

Replacing a simple string

Here’s an example:

let samplestr = "Hi, welcome to Universe!";
let newStr = samplestr.replace("Universe", "Itsourcecode"); 
console.log(newStr);

As you can see, we’re replace the word “Universe” with “Itsourcecode.” The replace() method returns a new string and does not modify the original string.

Output:

Hi, welcome to Itsourcecode!

Replacing a substring using a regular expression

You have the option to utilize the replace() method alongside regular expressions. It allows you to replace not only complete words but also parts of words, granting you greater flexibility and control.

Here’s an example:


let samplestr = "Today is a family day. I love family day!";
let newStr = samplestr.replace(/family/g, "Christmas"); ✅

console.log(newStr);

As you can see, we use the regular expression /family/g to find all occurrences of the word of the substring “family” in the samplestr.

When you include the “g” flag, it means you want to replace all the matches. The replacement string “Christmas” replaces all matched substrings, resulting in the newStr.

Output:

Today is a Christmas day. I love Christmas day!

Here’s another example example:

let samplestr = "I love math. Math is my favorite subject.";
let newStr = samplestr.replace(/Math/gi, "Programming"); 
console.log(newStr); 

Here, we replace all occurrences of the subject “Math” with “Programming.”

We use a regular expression /Math/gi to find all occurrences of the word ” Math,” regardless of the case. It is because the /i flag is used in a case-insensitive search.

(That’s why we used the “i” flag here), and replace them with “Programming.”

Output:

I love Programming. Programming is my favorite subject.

Replacing a substring using a function

You can also pass a function as the second argument to the replace() method. This function’s return value will be used as the replacement string.

Here’s an example:

let samplestr = "I have 2 cookies in my bag.";
let newStr = samplestr.replace(/\d+/, function(match) { 
    return parseInt(match) * 2;
});
console.log(newStr); 

In this example, we used regular expression to match any sequence of digits in the string (which represents the number of cookies).

The matched substring is passed to the function, where it’s doubled and returned. The replace() method then uses this return value as the replacement string.

Output:

I have 4 cookies in my bag.

Replacing multiple different substrings

If you want to replace multiple different substrings in a string, you can chain replace() methods:


let samplestr = "I love Math and English subjects.";
let newStr = samplestr.replace("Math", "Programming").replace("English", "Software Engineering"); ✅
console.log(newStr);

In this example, we replace “Math” with “Programming” and “English” with “Software Engineering.”

Each replace() method returns a new string, so you can chain them together to perform multiple replacements.

Output:

I love Programming and Software Engineering subjects.

Conclusion

The replace() method in JavaScript is used to replace a string or substring with another string or the result of a function.

This method is versatile and can be used with simple strings or regular expressions for more complex patterns.

Remember, the replace() method does not modify the original string but returns a new string with the replacements.

It makes it a safe operation that won’t accidentally alter your original data.

Whether you’re replacing simple strings, using regular expressions, or passing a function as an argument, the replace() method offers flexibility and control in handling string replacements.

We are hoping that this article provides you with enough information that help you understand how to replace substring in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment