// Tutorial //

How To Replace All Instances of a String in JavaScript

Published on December 12, 2019 · Updated on October 27, 2020
Default avatar

By Chris Sev

Sr Developer Advocate

How To Replace All Instances of a String in JavaScript

Introduction

Replacing text in strings is a common task in JavaScript. In this article, you’ll look at using replace and regular expressions to replace text.

Prerequisites

  • A familiarity with the Javascript programming language. Visit our tutorial series, How To Code in Javascript, to learn the basics.

Replacing a Single Instance

Normally JavaScript’s String replace() function only replaces the first instance it finds in a string:

app.js
const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace('sentence', 'message');
console.log(newMessage); // this is the message to end all sentences

In this example, only the first instance of sentence was replaced.

Replacing Multiple Instances

If you want JavaScript to replace all instances, you’ll have to use a regular expression using the /g operator:

app.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

This time both instances are changed.

In addition to using the inline /g , you can use the constructor function of the RegExp object:

app.js
const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message');
console.log(newMessage); // this is the message to end all messages

Replacing Special Characters

To replace special characters like -/\^$*+?.()|[]{}), we’ll need to use a backslash to escape them.

Here’s an example. Given the string this\-is\-my\-url, let’s replace all the escaped dashes (\-) with an unescaped dash (-).

You can do this with replace():

app.js
const myUrl = 'this\-is\-my\-url';
const newUrl = myMessage.replace(/\\-/g, '-');
console.log(newUrl); // this-is-my-url

Alternatively, use new Regexp():

app.js
const myUrl = 'this\-is\-my\-url';
const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');
console.log(newUrl); // this-is-my-url

In this second example, you don’t have to use a backslash to escape the backslash.

Conclusion

In this article, you saw how to replace single instances, multiple instances, and how to handle strings with special characters.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Chris Sev

author

Sr Developer Advocate

Founder of scotch.io. Slapping the keyboard until good things happen.



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Since ES2021, you could also use String.prototype.replaceAll().

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel
Get started for free

Enter your email to get $200 in credit for your first 60 days with DigitalOcean.

New accounts only. By submitting your email you agree to our Privacy Policy.

© 2023 DigitalOcean, LLC.