This quick tutorial will show you how to find and replace text in JavaScript, with code examples.
Replacing text in strings is something you will probably need to do quite often. JavaScript comes with the replace() method as part of it’s String objects to handle this functionality.
JavaScript Strings
JavaScript Strings are a type of variable used to store and manipulate a sequence of characters. There are also string primitives which represent only the characters and do not contain methods for manipulation, but JavaScript will implicitly convert between the two when required.
The replace() Method for Finding and Replacing Text
Javascript String objects contain the replace() method, for, you guessed it, searching for text and replacing it.
replace() Method Syntax
The syntax for the replace() method is as follows:
STRING.replace(SEARCH, NEWSTRING)
Note that:
- STRING is any string typed variable or value
- SEARCH is either the string to search for, or the regular expression of the text you wish to find
- Only the first found match will be replaced if searching for a string or using regular expressions
- NEWSTRING is the text which will replace any text found by SEARCH
- replace() does not modify the original STRING – a new value is returned
JavaScript replace() Method Examples
Below a string is defined, and then a replacement is made and printed:
var myString = "the quick brown fox"; console.log(myString.replace("fox", "frog")); // "the quick brown frog"
Note that the original value of myString has not been changed – the result of the replacement has just been printed. To retain the updated string, it must be assigned to a new variable:
var myString = "the quick brown fox"; var updatedString = myString.replace("fox", "frog");
Regular expressions can be included in the search. Below, upper/lower case is ignored when searching using the i expression:
var myString = "the quick brown fox"; console.log(myString.replace(/FOX/i, "frog"));