Eventually everyone came across the case that JavaScriptâs replace function, which is available on a JavaScript string primitive , does only replace one occurrence of the matched term.
Here I want to show you briefly how to replace all occurrences in JavaScript with two different ways. The first way uses a regular expression to find all matches with a global flag :
Without the global flag, the regex would only match one occurrence. An alternative to this is JavaScriptâs replaceAll function, which is built-in for JavaScript string primitives, but not available for all browsers yet:
While replaceAll isnât fully available yet, you can use the regex version of replaceAll and the global flag g with JavaScriptâs replace version to replace all occurrences of a string.