English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript String replace() Method

 JavaScript String Object

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, usegModifiers (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.

Syntax:

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‹/›

Browser compatibility

All browsers fully support the replace() method:

Method
replace()YesYesYesYesYes

Parameter Value

ParameterDescription
oldValueThe value or regular expression to be replaced with the new value
newValueReplace the value of the search value (oldValue) with this value

Technical Details

Return Value:New string with part or all pattern matches is replaced with the new value
JavaScript Version:ECMAScript 1

More Examples

The following examples demonstrate the use of globalgModifiers 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‹/›

 JavaScript String Object