How to Replace a Word in a String in JavaScript

JavaScript provides several methods to manipulate strings, including replacing specific words or phrases. In this tutorial, we will explore how to replace a word in a string using the replace() method.

Using the replace() Method

The replace() method is used to search for a specified substring or regular expression in a string and replace it with a new substring. The syntax for this method is:


string.replace(searchValue, newValue);
    

Example 1: Replacing a Single Word

Here’s a simple example of how to replace a single word in a string:


const originalString = "Hello, world!";
const newString = originalString.replace("world", "JavaScript");
console.log(newString); // Output: "Hello, JavaScript!"
    

Example 2: Replacing All Instances of a Word

If you want to replace all instances of a word, you can use a regular expression with the global flag g:


const originalString = "JavaScript is great. I love JavaScript!";
const newString = originalString.replace(/JavaScript/g, "Python");
console.log(newString); // Output: "Python is great. I love Python!"
    

Example 3: Case Sensitivity

The replace() method is case-sensitive. If you want to replace a word without considering its case, you can use the following approach:


// Function to replace a word case-insensitively
function replaceCaseInsensitive(str, search, replacement) {
    const regex = new RegExp(search, 'gi'); // 'g' for global, 'i' for case-insensitive
    return str.replace(regex, replacement);
}

const originalString = "I love JavaScript and javascript!";
const newString = replaceCaseInsensitive(originalString, "javascript", "Python");
console.log(newString); // Output: "I love Python and Python!"
    

Final Thoughts

In this tutorial, you learned how to replace a word in a string using JavaScript’s replace() method. You also explored how to replace all instances of a word and handle case sensitivity. With these techniques, you can easily manipulate strings in your JavaScript applications!

Leave a Comment