JavaScript Glossary: String replace()

Written by Scotch.io - - Aggregated on Saturday February 9, 2019

Basics

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');

https://scotch.io/embed/gist/efe7fe257c9bfdc4d81aa654ddbb5bec

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.

Syntax

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.

https://scotch.io/embed/gist/b055d60ad8e0719501f71dfece728fd2

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.

https://scotch.io/embed/gist/fd957d8935a577a6666e85ae9d34f00d

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

https://scotch.io/embed/gist/452b0b9c2ff1d4ddf1ae3449f90ef595

Replace all special characters

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

https://scotch.io/embed/gist/d1d233fb4ff5264cd50b8208a03dcf84

Related Reading


« Some background to mine and my wife’s … - Michael Brooks - RSS Feed

Scotch.io - JavaScript Glossary: String repeat() »