- String.prototype.replaceAll()
- Try it
- Syntax
- Parameters
- Return value
- Exceptions
- Description
- JavaScript Replace – How to Replace a String or Substring in JS
- How to Replace a String or Substring with the replace() Method
- JavaScript String replace() Examples
- How to Replace Multiple Strings and Substring with the replace() Method
- How to Use replace() with Regular Expressions
- Case-sensitive Replacement with Regular Expressions
- Wrapping Up
- JavaScript String replace()
- Note
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Метод replace()
- Синтаксис
- Возвращаемое значение
- Примеры
String.prototype.replaceAll()
The replaceAll() method 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.
Try it
Syntax
replaceAll(pattern, replacement)
Parameters
Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.
If pattern is a regex, then it must have the global ( g ) flag set, or a TypeError is thrown.
Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace() .
Return value
A new string, with all matches of a pattern replaced by a replacement.
Exceptions
Thrown if the pattern is a regex that does not have the global ( g ) flag set (its flags property does not contain «g» ).
Description
This method does not mutate the string value it’s called on. It returns a new string.
Unlike replace() , this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.
function unsafeRedactName(text, name) return text.replace(new RegExp(name, "g"), "[REDACTED]"); > function safeRedactName(text, name) return text.replaceAll(name, "[REDACTED]"); > const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll() . In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).
If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.
For more information about how regex properties (especially the sticky flag) interact with replaceAll() , see RegExp.prototype[@@replace]() .
JavaScript Replace – How to Replace a String or Substring in JS
Joel Olawanle
When working with JavaScript, you might need to replace a string or substring with a new one.
For example, you might want to replace a certain string (like «color” — American English) or substring in a larger text or document with a different string (“colour” — British English). You may also want to replace certain characters or symbols from a string to make sure your program will work.
In this article, you will learn how to use JavaScript’s replace() method to replace a string or substring.
How to Replace a String or Substring with the replace() Method
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. The replace() method takes two arguments:
- The first argument is the string or regular expression to be replaced.
- The second argument is the string that will replace the matched string or regular expression.
// Syntax string.replace(searchValue, replaceValue)
In the syntax above, string is the string you want to perform the replacement on. The searchValue parameter is either a string or a regular expression that you want to search for in the string . The replaceValue parameter is the string that will replace the searchValue .
Note: Only the first instance will be replaced. If you want to replace all instances, you will have to use the replaceAll() method.
JavaScript String replace() Examples
Suppose you have a string that uses “color” which is America English and want to change “color” to “colour”, the British English form. Here is an example of how you can do this:
let originalString = "The color of the sky changes throughout the day."; let newString = originalString.replace("color", "colour"); console.log(newString);
This will replace “color” in the string and return a new string assigned to the variable newString .
"The colour of the sky changes throughout the day."
In a situation where you have more than one occurence of such substring, you can use the replaceAll method:
let originalString = "The color of the sky changes throughout the day, and sometimes the color of the clouds creates a beautiful contrast. The color of a flower can indicate its species, and the color of clothing can affect someone's mood."; let newString = originalString.replaceAll("color", "colour"); console.log(newString);
This will replace all instances of “color” in the string and return a new string assigned to the variable newString .
"The colour of the sky changes throughout the day, and sometimes the colour of the clouds creates a beautiful contrast. The colour of a flower can indicate its species, and the colour of clothing can affect someone's mood."
How to Replace Multiple Strings and Substring with the replace() Method
Sometimes you may want to change more than one string or substring in one string variable. For example, in the text below, you may want to change “color” to “colour” and “JS” to “JavaScript”.
let originalString = "Using JS, you can change the color of a webpage's background, text, and elements."
You can do that by chaining as many replace() methods as needed:
let originalString = "Using JS, you can change the color of a webpage's background, text, and elements."; let newString = originalString .replace("color", "colour") .replace("JS", "JavaScript"); console.log(newString);
This will return a new string with both instances replaced:
"Using JavaScript, you can change the colour of a webpage's background, text, and elements."
Also, you may want to replace multiple strings or substrings with just one string. For example, you may want to replace where “quick”, “fox”, and “brown” with one string — “hello”:
let originalString = "The quick brown fox jumps over the lazy dog."; let newString = originalString.replace(/quick|brown|fox/g, "hello"); console.log(newString); // Output: "The hello hello hello jumps over the lazy dog."
How to Use replace() with Regular Expressions
In JavaScript, you can use the replace() method with regular expressions to replace strings and substrings with more flexibility and power. For example:
let originalString = "Today is a sunny day. I love sunny days!"; let newString = originalString.replace(/sunny/g, "cloudy"); console.log(newString); // Output: "Today is a cloudy day. I love cloudy days!"
In this example, the regular expression /sunny/g matches all occurrences of the substring «sunny» in the originalString . The g flag specifies that all matches should be replaced. The replacement string «cloudy» replaces all matched substrings, resulting in the newString «Today is a cloudy day. I love cloudy days!»
Regular expressions can also be used to match patterns or groups of characters. For example:
let originalString = "My phone number is (123) 456-7890"; let newString = originalString.replace(/\D/g, ""); console.log(newString); // Output: "1234567890"
In this example above, the regular expression /\D/g matches all non-digit characters in the originalString . The \D character class matches any character that is not a digit. The g flag specifies that all matches should be replaced.
Case-sensitive Replacement with Regular Expressions
Regular expressions make it possible for you to perform advanced search and replace operations. For example, using the i flag, you can replace only strings and substrings whose case matches perfectly:
const originalString = "I love JavaScript and javascript loves me"; const newString = originalString.replace(/JavaScript/i, "Python"); console.log(newString); // Output: "I love Python and javascript loves me"
In this example, the replace() method replaces the first occurrence of the word «JavaScript» with «Python» in the originalString variable. The /i flag is used to perform a case-insensitive search.
Wrapping Up
In this article, you have learned how to replace a string or substring in JavaScript with the replace() method and the various instances in which the replace() method can work.
Hopefully, this article has given you a better understanding of how to use the replace() and replaceAll() method in JavaScript.
You can access over 188 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.
JavaScript String replace()
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
Note
See Also:
Syntax
Parameters
Parameter | Description |
searchValue | Required. The value, or regular expression, to search for. |
newValue | Required. The new value (to replace with). |
Return Value
More Examples
A global, case-insensitive replacement:
A function to return the replacement text:
let text = «Mr Blue has a blue house and a blue car»;
let result = text.replace(/blue|house|car/gi, function (x) return x.toUpperCase();
>);
Related Pages
Browser Support
replace() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Метод replace()
Метод replace() ищет строку для указанного значения или регулярного выражения и возвращает новую строку, где указанные значения будут заменены.
Применение: Метод не изменяет строку, для которой он вызывается.
Синтаксис
str.replace(regexp|substr, newSubStr|function[, flags])
regexp Объект регулярного выражения RegExp . Сопоставление заменяется возвращаемым значением второго параметра. substr Строка, которая должна быть заменена на newSubStr . Обратите внимание, будет заменено только первое вхождение искомой строки. newSubStr Строка, которая заменяет подстроку, полученную из первого параметра. Поддерживает несколько специальных шаблонов замены. function Функция, вызываемая для создания новой подстроки, размещаемой вместо подстроки из первого параметра. flags Строка, содержащая любую комбинацию флагов RegExp : g – глобальное соответствие, i – игнорировать регистр, m – соответствие по нескольким строкам. Этот параметр используется, только если первый параметр является строкой.
Возвращаемое значение
Новая строка, в которой указанные значения были заменены новым значением.
Этот метод не изменяет объект String, на котором он вызывается. Он просто возвращает новую строку.
Примеры
Если первым аргументом является строка, заменяется только первое вхождение подстроки в строку: