JavaScript Glossary: String replace()

Written by - - Aggregated on Saturday February 9, 2019


The String replace() method will look for a string in a string and replace it with another string. Stringception!

'this is my message'.replace('this', 'that');

Important Note: Replacing with a string will only replace the first instance. To replace all instances, use the RegExp with the /g flag. Examples below.


const newString = myString.replace(whatToSearchFor, whatToReplaceWith);

2 parameters

whatToSearchFor (string or regular expression)

The string that we want to search for with myString. This is what will be replaced.

whatToReplaceWith (string or function)

The replacement that will be inserted wherever we want.

Returns a new string

Returns a new string and does not change the original string.

Common Uses and Snippets

Replace http with https

Here's a quick function to switch http with https.

Replace all occurrences of a string

Normally String .replace() will only replace the first string it finds. If we want it to replace all strings, we have to use a regular expression to catch all the instances.

We can also use inline regular expressions like so: /sentence/g

Replace all special characters

To replace special characters, you have to escape them using \ . Here we're replacing \- with - in a url.

Related Reading

« Some background to mine and my wife’s … - Michael Brooks - RSS Feed - JavaScript Glossary: String repeat() »