14

I'm trying to make a local xml file parsing "application" for some colleagues and i'm using the current function to retrieve the files:

function ShowFolderFileList(folderspec) {
    var fso, f, f1, fc, s;
    fso = new ActiveXObject("Scripting.FileSystemObject");
    f = fso.GetFolder(folderspec);
    fc = new Enumerator(f.files);
    s = "";
    for (; !fc.atEnd(); fc.moveNext()) {
        var pathString = fc.item();
        $("#test").append(pathString + "<br />");
    }
}

The problem with this function it returns a string similar to:

C:\Users\SomeUser\Desktop\cool\Archief\CDATA1.xml

I need to replace the backward slashes to forward slashes of the entire string. How to do this?

I tried the replace method:

pathString.replace(/\\/g, "/")

But it doesn't seem to do the trick.

Can you guys help me out?

Radjiv
  • 141
  • 1
  • 1
  • 4

2 Answers2

20

The replace method does not alter the current instance of the string, but returns a new one. See if this works:

pathString = pathString.replace(/\\/g,"/");

See this example on jsfiddle.

David Pärsson
  • 6,038
  • 2
  • 37
  • 52
  • This only works because you've changed the output from the OP. He never had double slashes in his path. A single slash get's treated as an escaped character so your replace will not work. – Shannon Hochkins Oct 18 '16 at 03:18
  • No, I don't think so. I'm quite sure that `ActiveXObject("Scripting.FileSystemObject")` creates valid paths with properly escaped slashes. – David Pärsson Oct 18 '16 at 08:05
  • I agree that a non-escaped string won't work, as your example states. But then again, I'm quite sure that the OP's string _is_ properly escaped since in the OP's example shows it's created by a Microsoft library that provides file system access. – David Pärsson Oct 23 '16 at 11:44
3

If in your string you do not have two backslashes and ONLY one backslash, you can use String.raw

var myString = String.raw`C:\Users\SomeUser\Desktop\cool\Archief\CDATA1.xml`;
console.log(myString.replace(/\\/g, '/'));
PierBJX
  • 2,093
  • 5
  • 19
  • 50