String replace in Vanilla JS

— 3 minute read

First and formost 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 a good wat to start because you will learn the basics of JavaScript you need for any other plugins.

String replace in Vanilla JS permalink

Now to get to the essentials, how do we replace a string in VanillaJs. String replacement is a widely used developers goto and can even be used in Excel. 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 basically what we told it to do, so we need to use a regex to actually replace all occurrences.

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 passing 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);

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