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

Last modified date

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('/', ":");

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.


Let me know if you find it useful.

Hey there, my name is Rajesh, and I'm a Javascript developer ( currently working with Vue and Nuxt) working full time at a job I love. I have been a full-stack developer for several years and have worked on complex backend and database stuff in the past. I am now more focused on the frontend, UI/UX and web accessibility. I am very new to writing content, but I want to write more so I can help students and budding developers start their dream careers.