Subscribe

String replace in Vanilla JS

✍️

How to replace string in Vanilla JS or JavaScript

22 Mar, 2020 · 3 min read

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

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

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

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

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter