Latest web development tutorials

JavaScript replace () method

String Object Reference JavaScript String Object

Examples

In this example, we will implement a global replacement, whenever the "Microsoft" is found, it is replaced by "W3CSchool":

var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3CSchool");

n output:

Visit W3Schools!

try it"

Definition and Usage

replace () method is used to replace some characters and some characters or replace a regular expression matching substring in the string with.

If you want to know more please see the regular expression tutorial site: the RegExp tutorials and Our the RegExp Object Reference .

This method does not change the original string.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support replace () method.


grammar

string.replace(searchvalue,newvalue)

Parameter Value

参数 描述
searchvalue 必须。规定子字符串或要替换的模式的 RegExp 对象。
请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。
newvalue 必需。一个字符串值。规定了替换文本或生成替换文本的函数。

return value

类型 描述
String 一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。

technical details

JavaScript version: 1.2


More examples

Examples

Perform a global replacement:

var str="Mr Blue has a blue house and a blue car";
var n=str.replace(/blue/g,"red");

n output:

Mr Blue has a red house and a red car

try it"

Examples

Perform a global substitution ignoring case:

var str="Mr Blue has a blue house and a blue car";
var n=str.replace(/blue/gi, "red");

n output:

Mr red has a red house and a red car

try it"


String Object Reference JavaScript String Object