JavaScript Glossary - Lesson #29

JavaScript String .replace() Method

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

javascript
'this is my message'.replace('this', 'that');
js
// 1. create a message
const message = 'This is my message.';

// 2. replace message with new thing
// this creates a brand new string. does not change the original variable (message)
const newMessage = message.replace('message', 'new thing');

console.log(newMessage);
// 3. output: This is my new thing.

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.

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

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 and does not change the original string.

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

js
// 1. we have a url
const url = "http://better.dev";

// 2. replace http: with https:
const httpsUrl = url.replace("http:", "https:");

console.log(httpsUrl);
// 3. output: https://better.dev

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.

Replace All Instances of a Word

js
// 1. we have a sentence
const message = 'This is my store. In my store we store store store.'

// 2. replace all store with shop using a regular expression
// normally .replace() will only replace the 1st occurrence
const newMessage = message.replace(new RegExp('store', 'g'), 'shop');

// 3. output: This is my shop. In my shop we shop shop shop.
console.log(newMessage);

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

Replace All

js
const myMessage = 'this is the sentence to end all sentences';

const newMessage = myMessage.replace(/sentence/g, 'message');

console.log(newMessage); // this is the message to end all messages

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

js
const myUrl = 'this\-is\-my\-url';

// myMessage.replace(/\\-/g, '-');
// or
const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');

console.log(newUrl); // this-is-my-url

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)