The replace() method in JavaScript is used to search for a specified substring or regular expression pattern in a string, and then replace the first occurrence or all occurrences of that substring or pattern with a replacement string.
Syntax: string.replace(searchValue, replaceValue)
- searchValue: A string or regular expression pattern to search for within the original string.
- replaceValue: The string to replace the found substring or pattern with. It can also be a function to dynamically generate the replacement string.
Example:
let str = "Hello, World!";
let replacedStr = str.replace("World", "Universe");
console.log(replacedStr); // Output: "Hello, Universe!"
Explanation:
- We have a string str containing "Hello, World!".
- We use replace() to replace the substring "World" with "Universe".
- The resulting string, "Hello, Universe!", is stored in the variable replacedStr and logged to the console.
We can also use a regular expression as the search value, which provides more flexibility in matching patterns within the string. Additionally, we can use the 'g' flag to replace all occurrences of the search value, rather than just the first one.
Code Compiler Link: https://app.singhteekam.in/codecompiler/