You would use the replace method:

text = text.replace('old', 'new');

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.

Answer from sdleihssirhc on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ replace
String.prototype.replace() - JavaScript | MDN
The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence ...
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_replace.asp
JavaScript String replace() Method
The replace() method returns a new string with the value(s) replaced.
Discussions

replace - How can I perform a str_replace in JavaScript, replacing text in JavaScript? - Stack Overflow
JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - How do I replace all occurrences of a string? - Stack Overflow
Given a string: string = "Test abc test test abc test test test abc test test abc"; This seems to only remove the first occurrence of abc in the string above: string = string.replace('ab... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Does javascript have a method to replace part of a string without creating a new string? - Stack Overflow
Is there another method I can use, besides replace, that will alter the string in place without giving me a new string object? ... I suggest you never use reserved words (such as string) when defining variable names in any language. ... string is not a reserved word in JavaScript (source). More on stackoverflow.com
๐ŸŒ stackoverflow.com
string - How do I replace a character at a specific index in JavaScript? - Stack Overflow
In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it. You'll need to define the replaceAt() function yourself: More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
David Bushell
dbushell.com โ€บ 2024 โ€บ 02 โ€บ 01 โ€บ javascript-string-replace
Thought You Knew String Replace?
Pattern is usually a string or regular expression. Technically it can be any object with a Symbol.replace method (like a RegExp). Replacement is either a string or function that returns a string.
๐ŸŒ
Crio
crio.do โ€บ blog โ€บ how-to-replace-all-occurrences-of-a-string-in-javascript-2024-criodo
How Do I Replace All Occurrences of a String in JavaScript?
December 9, 2024 - In JavaScript, the replace() method is commonly used to modify strings by replacing parts of them.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ replaceAll
String.prototype.replaceAll() - JavaScript | MDN
The replaceAll() method of String values returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
๐ŸŒ
DEV Community
dev.to โ€บ maafaishal โ€บ javascript-stringreplace-useful-cases-3963
JavaScript `string.replace()` useful cases - DEV Community
September 24, 2024 - let str = "Hello World, World!"; let result = str.replace(/world/gi, "JavaScript") // Output: "Hello JavaScript, JavaScript!"
Find elsewhere
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ javascript โ€บ replace
JavaScript Replace Method: Advanced String Manipulation
You can also use string.prototype.replace, which is the built-in method directly tied to JavaScript strings for efficient string manipulation.
Top answer
1 of 16
5258

As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

Here is how this answer evolved:

str = str.replace(/abc/g, '');

In response to comment "what's if 'abc' is passed as a variable?":

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
2 of 16
2537

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.


Regular Expression Based Implementation

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Split and Join (Functional) Implementation

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

Check out this benchmark running these two implementations against each other.


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

๐ŸŒ
Medium
medium.com โ€บ @jfagbohungbe โ€บ using-the-string-replace-method-in-javascript-d03cee4d843e
Using the string.replace method in Javascript | by Oluwajuwon Fagbohungbe | Medium
October 18, 2019 - What we want to do is find all the characters in the given string that match either the underscore( _ ) or the hyphen (-) and the alphabets after them, transform them to uppercase letters and remove the non-alphabetic characters ยท First of all, since the replace method can take a regular expression to be used for matching, we can create an expression that matches what we want to replace.
๐ŸŒ
Bennadel
bennadel.com โ€บ blog โ€บ 142-ask-ben-javascript-string-replace-method.htm
Ask Ben: Javascript String Replace Method
April 18, 2020 - Since the function being passed to the replace method is a nested function, Javascript will search the local variable scope for "intCount." When it cannot find it, it will move up the scope chain to the CountValue() function which does contain a variable intCount. This is the variable that will be updated for each iteration of the loop. One last example that seems to stump a lot of people is the replacing of strings that span multiple lines.
๐ŸŒ
CoreUI
coreui.io โ€บ blog โ€บ how-to-replace-all-occurrences-of-a-string-in-javascript
How to replace all occurrences of a string in JavaScript? ยท CoreUI
August 31, 2024 - When dealing with large strings or performance-critical code, consider the following: Regular expressions are powerful but may introduce overhead. split and join are simple and effective for straightforward replacements. replaceAll is the most user-friendly but requires compatibility with modern JavaScript environments.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-replace-how-to-replace-a-string-or-substring-in-js
JavaScript Replace โ€“ How to Replace a String or Substring in JS
November 7, 2024 - In JavaScript, you can use the replace() method to replace a string or substring in a string. The replace() method returns a new string with the replacement.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How To Replace Part of a String - JavaScript String Replace (In 2 Mins) - YouTube
The string "replace" method in JavaScript lets you replace a substring with another value within a string. You can also use regular expressions for complex s...
Published: July 4, 2024
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how do i replace all occurrences of a string in javascript?
JavaScript replaceAll: Replace All String Occurrences | Sentry
Replace all occurrences of a substring in JavaScript using replaceAll with strings or regex, the replace method with a global flag, or split and join
๐ŸŒ
Bennadel
bennadel.com โ€บ blog โ€บ 2198-special-references-in-javascripts-string-replace-method.htm
Special $ References In JavaScript's String.replace() Method
April 21, 2020 - <!DOCTYPE html> <html> <head> <title>Using The $ In JavaScript RegEx Replace</title> <script type="text/javascript"> // Create a test string in which we will match our pattern. var value = "My number is 212-555-1234."; // Creat the pattern to match the phone number.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-string-replace-method
JavaScript string replace() Method - GeeksforGeeks
June 26, 2024 - It returns a new string with replaced items. Example 1: Below is an example of the string.replace() Method.