DEV Community

Rajesh Dhiman
Rajesh Dhiman

Posted on • Originally published at rajeshdhiman.in on

javaScript – Replace all occurrences of a forward slash in a string

Today I learned an easy solution to replace all occurrences of a forward slash in string in javascript. I had to convert an URL to a string in another format, so initially, I tried str.replace() method like

str.replace('/', ":");
Enter fullscreen mode Exit fullscreen mode

But to my surprise, it only replaced the first occurrence in the string.
Then I thought oh I might need to use a regular expression. But I failed to make a regular expression, I always do.
But then I find a much simple way.

str.split('/').join(':') 
Enter fullscreen mode Exit fullscreen mode

Let me know if you find it useful.

Top comments (6)

Collapse
 
aaroncql profile image
Aaron Choo

If you still need the regex way of doing this:

str.replace(/\//g, ":")
Enter fullscreen mode Exit fullscreen mode

Explanation: anything enclosed within a pair of forward slashes / signals that it is a regex. As such, we need to use the backslash to escape the forward slash to get \/. The g at the end is a flag to perform a global search, and thus replaces all occurrence of / with :.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Nicely put :)

Collapse
 
paharihacker profile image
Rajesh Dhiman

Thank you

Collapse
 
fluxthedev profile image
John

One and done function is better than two! Use this all the time.

Collapse
 
leoloopy profile image
Leo

I saw this exact method used to solve a problem on GitHub but I could not understand the use of forward slash and g. Thanks for this!

Collapse
 
jwp profile image
John Peters

Useful