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,'');

alert(noSlashes);


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.

5 comments on “Removing forward slashes from a string”

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

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

    alert(noSlashes);

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

  2. 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!)

  3. Hello,

    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

    Thanks

Add your comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>