19

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.

2
  • 3
    One might wonder about why someone would have such a problem. Commented Feb 2, 2011 at 4:30
  • stackoverflow.com/a/78921922/714707 - This answer with multiple solutions might help you Commented Aug 28, 2024 at 6:56

5 Answers 5

55

Try

str = str.replace(/\\/g, '');
Sign up to request clarification or add additional context in comments.

Comments

32

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

9 Comments

This does not fork if there is /" inside the string @Ates Goral
Does not work: try the string "corp\thomas". Will remove "\t".
@TomaszPlonka You might be getting the impression that it's removing it because \t is the escape sequence for the tab character.
@alper We're trying to remove backslashes (\) though. This is a forward slash: /.
ah sorry for misguiding
|
5

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;
}

Comments

1
Join Two Portions of a Path using
    function join(port1, port2) {
        let p1 = port1.split('/').join('');
        let p2 = port2.split('/').join('');
        let np = p1 + '/' +  p2;
        return np;
    }
    console.log(join("port1/", "/port2"))

Comments

1

"tset\ string \with backslash".split('\\').join('');

'tset string with backslash'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.