- JavaScript String Replace Using replace() Method
- JavaScript replace Method
- Syntax of replace method
- JavaScript replace String Examples
- # Example 1: Using string to match
- # Example 2: Using regexp to match
- # Example 3: Channing replace method
- Using a replacement function
- Syntax of replacement function
- Array Function As Replacement Function
- Switching Words In String
- Alternate method : Using Split and Join Method In Array
- Conclusion
- 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()
- Синтаксис
- Возвращаемое значение
- Примеры
JavaScript String Replace Using replace() Method
Here is quick learning of the replace() method in JavaScript using example. If you want to learn in detail then proceed further in this article.
// replace() method is used to replace a part // of a string with another string. // 1. Replace "Hello" with "Hi" in "Hello World" var str = "Hello World"; var newStr = str.replace("Hello", "Hi"); console.log(newStr); // Hi World // 2. Replace numbers with "." (using regex) var str = "Code12345"; var newStr = str.replace(/\d/g, "."); console.log(newStr); // Code. // 3. call a function for each match var str = "Hello World"; var newStr = str.replace(/o/g, function(match, index, originalText) < return "*" + match + "*"; >); console.log(newStr); // Hell*o* W*o*rld
JavaScript replace Method
The replace() method in JavaScript is used to replace a part of a string with another string. It matches a pattern within the string using a string or regular expression and replaces it with a replacement string or a function .
The original string is not modified. The method returns a new string by replacing one or all matches of the calling string.
The search pattern in the method could be a string or a regex .
- string — If the given pattern is a string then the method replaces only the first match in the string
- regex — if the pattern is a regex then it replaces all the occurrences of the matching pattern with the replacement string
const str = "to do or not to do."; // string search pattern const pattern1 = "do"; console.log(str.replace(pattern1, "be")); // to be or not to do. // regex search pattern const pattern2 = /do/g; console.log(str.replace(pattern2, "be")); // to be or not to be.
You can see in the above example when the matching pattern is a string then it replaces only the first match (‘do’), but when using regex as a matching pattern then it finds all the matches and replaces it.
One thing to note is we have used the /g flag in the regex if you don’t use the /g flag then it replaces only the first occurrence just like string.
Syntax of replace method
The syntax of replace() method is as follows:
str.replace(substr, new_string); str.replace(regexp, new_string); str.replace(substr, function); str.replace(regexp, function);
- substr — It is the string that is to be replaced by the new_string . It is treated as a literal string and is not treated as a regular expression, so only the first occurrence of this is replaced.
- regexp — It is the regular expression, the pattern used to replace the match or matches with new_string .
- new_string — It is the replacement string that replaces the matches by the pattern.
- function — It is a function that is invoked for every match of the pattern in the string. The return value of the replacement function is used to replace the matching string. This function is discussed in detail below.
Note : The original string is untouched by the replace() method, a new string is returned after replacement.
JavaScript replace String Examples
Now as we have discussed the replace() method and gone through its syntax let’s now see various examples using string and regex.
# Example 1: Using string to match
The following example uses a substring to match content and replace it with a new string. When regex is used then it finds all the matchings within the string and replaces it with a new string using replace() method.
const str = "to do or not to do."; const pattern = "do"; // string console.log(str.replace(pattern, "Sleep")); // to Sleep or not to do.
# Example 2: Using regexp to match
The following example uses a regular expression to match content and replace it with a new string. As it is a string so only the first match is replaced by the new string when using replace() method.
const str = "to do or not to do."; const pattern = /do/g; // regex console.log(str.replace(pattern, "Sleep")); // to Sleep or not to Sleep.
Note : Use /g flag with regex, if not used then it will only replace the first match.
const str = "to do or not to do."; const pattern = /do/; // no g flag console.log(str.replace(pattern, "Sleep")); // to Sleep or not to Sleep.
# Example 3: Channing replace method
Suppose you want to replace 2 more than 2 different substrings within a string with another new string. So the basic idea to do this would be to replace one by one different matches and assign a return value every time to the original string, as shown in the example below.
let str = "To do or not to do."; str = str.replace(/do/gi, 'code'); // replace all do with code str = str.replace(/to/gi, 'love'); // replace all to with love console.log(str); // love code or not love code.
But instead of doing this you can chain the replace() method and do this in a single line of code.
let str = "To do or not to do."; str = str.replace(/do/gi, "code").replace(/to/gi, "love"); // replace all do with codeand replace all to with love console.log(str); // love code or not love code.
Using a replacement function
The replace method can also accept a replacement function instead of a new string as the second parameter.
let newString = str.replace(substr | regex, replacement_function);
When a replacement function is used then it will invoke after the match has been performed.
For multiple matches when used regular expression with /g flag it will be invoked for each match from the string.
The return value of the replacement function is used as a new string to replace matchings.
const str = "to do or not to do."; const pattern = /do/g; function replacer() < return "Sleep"; >console.log(str.replace(pattern, replacer)); // to Sleep or not to Sleep.
In the above example, you can see the return value of the replacement function is used as a new string to replace the matches.
Syntax of replacement function
function replacer(match, p1, p2, . offset, string) <>
The arguments of the replacement function are as follows:
Parameter | Description |
---|---|
match | Matching part of the string by the pattern |
p1, p2, . | This is the string found by parenthesized capturing group in series. This means p1 will be the first capture of capturing group, p2 will be the second, and so on. |
offset | It is the index value of matched substring within the string. |
string | The string method is called upon |
The following example shows for what match the string is replaced by using the replacement function.
Using match in replacement function
const str = "to do or not to do."; const pattern = /do/g; function replacer(match) < return `($) => Sleep`; > console.log(str.replace(pattern, replacer)); // to Sleep or not to Sleep.
The following example shows the captures of the capturing group by the regex.
const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1) < return `($) => Sleep \n(capturing $)\n`; > console.log(str.replace(pattern, replacer));
This example shows the captures offset of the capturing group within the string.
const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1, offset) < return `($) => Sleep \n(capturing $) at index $\n`; > console.log(str.replace(pattern, replacer));
This example uses all the parameters of the replacement function.
const str = "to do or not to do."; const pattern = /d(o)/g; function replacer(match, p1, offset, string) < return `($) => Sleep \n(capturing $) at index $ in ($)\n`; > console.log(str.replace(pattern, replacer));
Array Function As Replacement Function
The array function can also be used as a replacement function for the replace() method. You can either directly put it in the method as an anonymous function or use a function with a name.
const str = "to do or not to do."; const pattern = /d(o)/g; const newString = str.replace(pattern, (match, p1, offset, string) => < return `($) => Sleep \n(capturing $) at index $ in ($)\n` >) console.log(newString);
Switching Words In String
Use $n to catch the words to switch in the string. The $n represents the nth parenthesized capturing word, where n is a positive integer less than 100.
const str = 'Do Be do be'; const regexp = /(\w+)\s(\w+)\s(\w+)\s(\w+)/; const newstr = str.replace(regexp, "$2 $1, $4 $3"); console.log(newstr); // Be Do, be do
Alternate method : Using Split and Join Method In Array
Instead of using replace() method, you can use a combination of split and join method to create the same functionality.
Split the string from the matching string you want and join them using the join method and use the new string as a separator. See the example below.
const str = "to do or not to do."; const subStr = "do"; const replaceBy = "Sleep"; const newStr = str.split(subStr).join(replaceBy); console.log(newStr);
The above example split the string using the split method at «do» and join them using «Sleep» as a separator in the join method.
Conclusion
In this tutorial, you learned everything about the replace() method and it’s uses. The method can be used to replace a string with another string or call a function for each match in the string.
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, на котором он вызывается. Он просто возвращает новую строку.
Примеры
Если первым аргументом является строка, заменяется только первое вхождение подстроки в строку: