JavaScript String replace() Method | javascript string replace
ExamplesReplaceMicrosoft:lettext="VisitMicrosoft!";letresult=text.replace("Microsoft","W3Schools");TryitYourself»[1]Aglobalreplacement:lettext="MrBluehasabluehouseandabluecar";letresult=text.replace(/blue/g,"red");TryitYourself»[2]Moreexamplesbelow.DescriptionThereplace()methodsearchesastringforavalueoraregularexpression.Thereplace()methodreturnsanewstringwiththevalue(s)replaced.Thereplace()methoddoesnotchangetheoriginalstring.NoteIfyoureplaceavalue,onlythefirstinstancewillbereplaced.Torepla...
ExamplesReplace Microsoft:
let text = "Visit Microsoft!";let result = text.replace("Microsoft", "W3Schools");
Try it Yourself »[1]A global replacement:
let text = "Mr Blue has a blue house and a blue car";let result = text.replace(/blue/g, "red");
Try it Yourself »[2]More examples below.
DescriptionThe 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.
NoteIf you replace a value, only the first instance will be replaced. To replace all instances, use a regular expression with the g modifier set.
Read more about regular expressions in our:
See Also:The replaceAll() Method[3] - replaces all matches
Syntaxstring.replace(searchValue, newValue)
Parameters Parameter Description searchValue Required.The value, or regular expre...