How to replace a string? JavaScript essentials

/ #JavaScript


Replacing strings in JavaScript can be done in many different ways. In this guide, I'll show you a couple of them.

Replacing one occurance

In this example, I'll show you how to use the "replace" function to replace one occurance of a string in a string:

var str = "This is a string";
var result = str.replace("string", "sentence");
console.log(result);

If you run this code in your browser, you will see this sentence in your console log: "This is a sentence". So the first value you pass in is the word you search for, and the second value you pass in is the value you want to replace it with.

If you change the value of the "str" variable to this "This is a string and more string", it will still only replace the first occurance.

Replacing all occurances

Almost all of the times, you want to replace all of the occurances of a word in a string. To do this, we need to perform a global replacement using regular expressions. This isn't as hard as it sounds. Let me show you an example:

var str = "This is a string with more than one string.";
var result = str.replace(/string/g, "sentence");
console.log(result);

If you run this in your browser, the console log will say "This is a sentence with more than one sentence."

The global replace is case sensitive, so you need to modify the expression above if you want to replace both lowercase and uppercase occurances. The only thing you need to do, is to replace the "g" after the "/" with "gi". That means that it's global and insensitive.

Other relevant JavaScript tutorials

How to check if a string starts with a certain word
How to split a string

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.