Removing backslashes from strings in javascript

57,020

Solution 1

Try:

string.replace(/\\\//g, "/");

This will specifically match the "\/" pattern so that you don't unintentionally remove any other backslashes that there may be in the URL (e.g. in the hash part).

Solution 2

Try

str = str.replace(/\\/g, '');

Solution 3

from: http://knowledge-serve.blogspot.com/2012/08/javascript-remove-all-backslash-from.html

function replaceAllBackSlash(targetStr){
    var index=targetStr.indexOf("\\");
    while(index >= 0){
        targetStr=targetStr.replace("\\","");
        index=targetStr.indexOf("\\");
    }
    return targetStr;
}
Share:
57,020
Franz Payer
Author by

Franz Payer

Updated on January 29, 2020

Comments

  • Franz Payer
    Franz Payer over 4 years

    I have a url in this format:

    http:\/\/example.example.ru\/u82651140\/audio\/song.mp3

    How can I remove the extra "\"s from the string? I have tried string.replace("\","") but that does not seem to do anything. If you could give me a JavaScript regular expression that will catch this, that would also work too. I just need to be able capture this string when it is inside another string.

  • alper
    alper about 6 years
    This does not fork if there is /" inside the string @Ates Goral
  • Tomasz Plonka
    Tomasz Plonka over 3 years
    Does not work: try the string "corp\thomas". Will remove "\t".
  • Ates Goral
    Ates Goral over 3 years
    @TomaszPlonka You might be getting the impression that it's removing it because \t is the escape sequence for the tab character.
  • Ates Goral
    Ates Goral over 3 years
    @alper Can you be more specific? Do you mean "/\""?
  • alper
    alper over 3 years
    I believe I meant the string we want to replace contains /" your answer does not work
  • Ates Goral
    Ates Goral over 3 years
    @alper The question and my answer was about removing backslashes and nothing else. Can you give an example of the full string?
  • Ates Goral
    Ates Goral over 3 years
    @alper /"hello/" is not valid JS. I'm confused.
  • Ates Goral
    Ates Goral over 3 years
    @alper We're trying to remove backslashes (\) though. This is a forward slash: /.
  • alper
    alper over 3 years
    ah sorry for misguiding