Removing forward slashes from a string

All I wanted was to remove all forward slashes in a string using Javascript. It turns out that’s more complicated than you’d think and after multiple searches on Google I finally found the answer, in a comment on somone’s post.

A quick test can be written as follows:

myUrlString = "/apple/banana/satsuma/";

noSlashes = myUrlString.replace(/\//g,'');


The important part to note here is the regular expression /\//g. The piece of the string you want replacing is written between the first and last forward slashes – so if you wanted the word ‘desk’ replaced you would write /desk/g.

As the character we want to remove is a special case you have to escape it using a backslash, otherwise the code will read the double forward slash as a comment and so stop processing the line.

Finally, the g means apply the replacement globally to the string so that all instances of the substring are replaced.