In this blog post you’ll learn about the JavaScript replace() method. The method to replace the specified value with another value.
Description:
replace() method search in string for a specified value (with regular expression or normal value) and replace with another given value.
replace() method does not change original string.
Syntax:
JavaScript
text.replace(SearchValue, ValueToReplace);
Parameter Description.
SearchValue: Value to search for replacement. (Required)
ValueToReplace: New Value to replace with given SearchValue . (Required).
Example 1: Replace specific word in string.
JavaScript
let text = "Hello Good morning!. Welcome to maketechstuff.com";
let replaced_text = text.replace("morning", "afternoon");
document.write(replaced_text);
// Output:
// Hello Good afternoon!. Welcome to maketechstuff.com
Given search value in regular expression.
JavaScript
let text = "Hello Good morning!. Welcome to maketechstuff.com";
let replaced_text = text.replace(/morning/g, "afternoon");
document.write(replaced_text);
// Output:
// Hello Good afternoon!. Welcome to maketechstuff.com
Case in-sensitive.
JavaScript
let text = "Hello Good Morning!. Welcome to maketechstuff.com";
let replaced_text = text.replace(/morning/gi, "afternoon");
document.write(replaced_text);
// Output:
// Hello Good afternoon!. Welcome to maketechstuff.com
So that is how the JavaScript replace() method works. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.