Categories
JavaScript Answers

How to perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript?

Spread the love

Sometimes, we want to perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript.

In this article, we’ll look at how to perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript.

How to perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript?

To perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript, we can use the RegExp constructor.

For instance, we write

const myString = "hello world test world";
const find = "world";
const regex = new RegExp(find, "g");
console.log(myString.replace(regex, "yay"));

to create a regex that matches all instances of the find string by calling it with find and 'g'.

Then we call myString.replace with regex and 'yay' to replace all instances of 'world' with 'yay'.

Conclusion

To perform a global replace on string with a variable inside ‘/’ and ‘/g’ in JavaScript, we can use the RegExp constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *