How to fix JavaScript .replace only replaces first match?

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.