URL: https://www.progressiverobot.com/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

replace illustration for: 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:

				
					
[label 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:

				
					
[label 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:

				
					
[label 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():

				
					
[label app.js]

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

const newUrl = myMessage.replace(/\\-/g, '-');

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

				
			

Alternatively, use new Regexp():

				
					
[label 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.