Categories
JavaScript Answers

How to fix JavaScript .replace only replaces first match?

Spread the love

Sometimes, we want to fix JavaScript .replace only replaces first match.

In this article, we’ll look at how to fix JavaScript .replace only replaces first match.

How to fix JavaScript .replace only replaces first match?

To fix JavaScript .replace only replaces first match, we can use the replace method with a regex with the g flag.

For instance, we write

const textTitle = "this is a test";
const result = textTitle.replace(/ /g, "%20");
console.log(result);

to call replace with / /g to replace all spaces with "%20".

The g flag will make replace replace all instances of the match.

Conclusion

To fix JavaScript .replace only replaces first match, we can use the replace method with a regex with the g flag.

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 *