The replace()
method in JavaScript is a versatile tool for manipulating strings by finding and replacing specific values or patterns within them. It's widely used in tasks such as:
The replace()
method takes two arguments:
searchValue
.replace()
method doesn't modify the original string. Instead, it creates a new string with the replacements applied.replace()
method to search for complex patterns and perform powerful replacements.The replace()
method is an ECMAScript1 (ES1) feature, which means it's fully supported in all modern web browsers, including:
You can confidently use this method in your JavaScript code without worrying about compatibility issues.
Let's explore some practical examples to see how the replace()
method works in action.
Example 1: Replacing a Simple String
let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
console.log(result); // Output: Visit W3Schools!
Example 2: Global Replacement with Regular Expressions
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/g, "red");
console.log(result); // Output: Mr Red has a red house and a red car
Example 3: Case-Insensitive Replacement
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/gi, "red");
console.log(result); // Output: Mr Red has a red house and a red car
Example 4: Replacing with a Function
let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue|house|car/gi, function (x) {
return x.toUpperCase();
});
console.log(result); // Output: Mr BLUE has a BLUE HOUSE and a BLUE CAR
While the replace()
method is versatile, it only replaces the first occurrence of the searchValue
by default. For global replacements (replacing all instances), you can use the replaceAll()
method.
Note: replaceAll()
is a newer method, and its browser support is not as widespread as replace()
. However, it offers a cleaner and more efficient way to perform global replacements.
The replaceAll()
method is an ECMAScript2021 (ES12) feature. It has good support in modern browsers, but you might need to use polyfills for older browsers.
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | No |
For better browser support and compatibility, it's generally recommended to use the 'g' flag with the replace()
method for global replacements unless you specifically require replaceAll()
for its specific features.
The replace()
method provides a powerful way to search and replace values in strings. By understanding its functionality and utilizing regular expressions and the replaceAll()
method (where supported), you can efficiently manipulate strings in your JavaScript code.
Ask anything...