snippetjavascriptTip
Replace all occurrences of a string in JavaScript
Viewed 0 times
javascriptreplacealloccurrencesstring
Problem
Modern JavaScript engines have a built-in method called
Using
Before the introduction of
While this method doesn't replace all occurrences of a string, it supports regular expressions. Knowing the string to be replaced, a regular expression can be created with the global (
String.prototype.replaceAll(). This method can be used to replace all occurrences of a string in another string with relative ease.Using
String.prototype.replaceAll() is the recommended approach, as it's straightforward. If, however, you need to support older browsers, consider the option below.Before the introduction of
String.prototype.replaceAll(), String.prototype.replace() was the method of choice for this sort of task. It's supported by all JavaScript engines, old and new and is very similar to String.prototype.replaceAll().While this method doesn't replace all occurrences of a string, it supports regular expressions. Knowing the string to be replaced, a regular expression can be created with the global (
'g') flag. Then, it can be passed to String.prototype.replace() to replace all occurrences of the string. The only issue here is that special characters need to be escaped, so that they are matched correctly. The escapeRegExp code snippet comes in handy for this task.Solution
const str = 'Hello World';
str.replaceAll('o', 'x'); // 'Hellx Wxrld'Before the introduction of
String.prototype.replaceAll(), String.prototype.replace() was the method of choice for this sort of task. It's supported by all JavaScript engines, old and new and is very similar to String.prototype.replaceAll().While this method doesn't replace all occurrences of a string, it supports regular expressions. Knowing the string to be replaced, a regular expression can be created with the global (
'g') flag. Then, it can be passed to String.prototype.replace() to replace all occurrences of the string. The only issue here is that special characters need to be escaped, so that they are matched correctly. The escapeRegExp code snippet comes in handy for this task.Code Snippets
const str = 'Hello World';
str.replaceAll('o', 'x'); // 'Hellx Wxrld'const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const replaceAll = (str, subStr, newSubStr) =>
str.replace(new RegExp(escapeRegExp(subStr), 'g'), newSubStr);
const str = 'Hello World';
replaceAll(str, 'o', 'x'); // 'Hellx Wxrld'Context
From 30-seconds-of-code: replace-all-occurences-of-string
Revisions (0)
No revisions yet.