replace() method provided by the String prototype object.
replace() method is used to replace a single occurrence of a substring with a replacement string that you provide as its arguments. The method accepts 2 arguments as follows:
pattern- The substring pattern to look for. Can be a string or a regular expression.
replacement- A string used to replace the substring match by the provided pattern.
You can remove a substring by passing an empty string as the
The following example shows how to remove the substring ‘abc’ from
const myString = 'abcdef abcxys'; // Remove 'abc' substring const newString = myString.replace('abc', ''); console.log(newString); // def abcxys
Here, you can see that the string ‘abc’ in front of the string is removed, but the second occurrence is ignored by the
replace() method. This is because
replace() only checks for a single occurrence of the substring from your string.
If you want to remove all occurrences of the substring, you need to use the
replaceAll() method instead. Here’s an example:
const myString = 'abcdef abcxys'; // Remove 'abc' substring const newString = myString.replaceAll('abc', ''); console.log(newString); // def xys
In the above example, you can see that the ‘abc’ substrings are removed, leaving only ‘def’ and ‘xys’ on the string.