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.

Tags: ,

5 Responses to “Removing forward slashes from a string”

  1. pawan says:

    myUrlString = “/apple/banana/satsuma/”;

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


    this is not working in javascript, it treat 2nd as a comment..
    checked it out..

  2. Emma says:

    @pawan – I don’t know what to say, apart from it does work :)

  3. vaelico says:

    In case someone wonders why Pawan says it isn’t working;

    The second argument of the replace function is an empty string between two single quotes, as shown in the post body (good). Please notice that in Pawan’s comment, there is only one double-quote character (wrong!)

  4. Emma says:

    @vaelico good spot, thanks for the clarification!

  5. xohaib says:


    Please help me. I want to write a java program in which i write a string in backslash and forwardslash but slashes will never show. e.g;
    / \, // \\, /// \\\ just like / Hello World \, //Hello world \\ and /// Hello World \\\ and slashes will remove in output.
    required output will show as:
    Hello World
    Hello World
    Hello World


Leave a Reply