English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
replace()The method is used to replace some characters with other characters in a string, or to replace a substring that matches a regular expression.
The pattern can be a string or a regular expression, and the replacement can be a string or a function called for each match.
If the pattern is a string, only the first match will be replaced.
To replace all occurrences of the specified value, useg
Modifiers (global search) (see the following 'More Examples').
You can find inRegExp tutorialandReference in RegExp objectsLearn more about regular expressions.
Note:This method does not change the original string value.
string.replace(oldValue, newValue)
var str1 = 'The question is to be, or not to be, that is to be.'; var str2 = str1.replace('to be' 'ZZZ');Test and see‹/›
All browsers fully support the replace() method:
Method | |||||
replace() | Yes | Yes | Yes | Yes | Yes |
Parameter | Description |
---|---|
oldValue | The value or regular expression to be replaced with the new value |
newValue | Replace the value of the search value (oldValue) with this value |
Return Value: | New string with part or all pattern matches is replaced with the new value |
---|---|
JavaScript Version: | ECMAScript 1 |
The following examples demonstrate the use of globalg
Modifiers used with replace():
var str1 = 'The question is to be, or not to be, that is to be.'; var str2 = str1.replace(/to be/g, 'ZZZ');Test and see‹/›
The following examples demonstrate how to use the global and ignore case modifiers with replace():
var str1 = 'The question is TO BE, or not to be, that is to be.'; var str2 = str1.replace(/to be/gi, 'ZZZ');Test and see‹/›