Categories
JavaScript Answers

How to globally replace a forward slash in a JavaScript string?

Spread the love

Sometimes, we want to globally replace a forward slash in a JavaScript string.

In this article, we’ll look at how to globally replace a forward slash in a JavaScript string.

How to globally replace a forward slash in a JavaScript string?

To globally replace a forward slash in a JavaScript string, we call the string replace method with a regex with the g flag.

For instance, we write

const s = "/string/".replace(/\//g, "ForwardSlash");

to call '/string/'.replace with the regex /\//g and 'ForwardSlash' to replace the forward slashes in '/string/' with 'ForwardSlash'.

Conclusion

To globally replace a forward slash in a JavaScript string, we call the string 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 *