String replace in Vanilla JS

β€” 4 minute read

permalink

First and foremost, you will see me use Vanilla JS/Plain Javascript or JavaScript throughout my post. I'm a big fan of Vanilla JavaScript. This is the plain version of JavaScript without using plugins like jQuery. VanillaJs is an excellent way to start because you will learn the basics of JavaScript you need for any other plugins.

String replace in Vanilla JS permalink

Now, how do we replace a string in VanillaJs. String replacement is a widely used developer's goto. In plain Javascript is as simple as the following example:

let input =
"search for me, i'm hidden. You can search but it doesn't mean your search will work.";
let output = input.replace('search', 'found');
console.log(output);

This will output: "found for me, i'm hidden. You can search but it doesn't mean your search will work."

You may wonder why it only replaces 1 "search" this is what we told it to do, so we need to use a regex to replace all occurrences.

Note: We can also use replaceAll these days, as you can see in this artilce.

Regex string replace in Vanilla JS permalink

let input =
"search for me, i'm hidden. You can search but it doesn't mean your search will work.";
const regex = new RegExp('search', 'g');
let output = input.replace(regex, 'found');
console.log(output);

This will output: "found for me, i'm hidden. You can found but it doesn't mean your found will work."

So this option worked. We made a regex to search for "search" "globally". We defined globally by using the g option to the RegExp, Read more about it here

We can also use the shorthand like this:

let input =
"search for me, i'm hidden. You can search but it doesn't mean your search will work.";
let output = input.replace(/search/g, 'found');
console.log(output);

Modern JavaScript solution permalink

In modern JavaScript, we can leverage an even better method called replaceAll this is a mix of the above, but in a neat JavaScript function.

let input =
"search for me, i'm hidden. You can search but it doesn't mean your search will work.";
let output = input.replaceAll('search', 'found');
console.log(output);

Which will output:

This will output: "found for me, i'm hidden. You can found but it doesn't mean your found will work."

Feel free to play around with this codepen:

See the Pen String replace in Vanilla JS by Chris Bongers (@rebelchris) on CodePen.

Now you know the string replace in VanillaJS permalink

As always, feel free to reach out on Facebook or Twitter if you have any questions, tips or topics you want to see. πŸ‘‹