Removing forward slashes from a string
TweetAll 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.
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..
@pawan – I don’t know what to say, apart from it does work :)
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!)
@vaelico good spot, thanks for the clarification!
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