2

I have a javascript file that is ran through a windows job using cscript. However, I can't seem to fix this thing to work correctly. Inside the file, it basically takes a URL and transforms it to a UNC path.

ex: http://mysite.com/document1.htm to \myserver\document1.htm

However, I can't seem to get the /'s to goto \'s and am at a loss why.

I've tried 2 things basically

1) str = str.replace(/\/g, "\\");
2) str = str.replace("/", "\\");

Any idea why it wont work?

Thanks, Dave

1
  • +1 Really interesting, after it replaces the first slash, it makes it scape the second.. really interesting.. Commented Apr 20, 2011 at 19:57

2 Answers 2

9

It's like this:

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

the / on the end is the normal /pattern/ format, you need an extra for your \ escape, you can test it out here.

Sign up to request clarification or add additional context in comments.

5 Comments

And str = str.replace("/", "\\"); does not work because, unless otherwise noted (by a regex with the g modifier), JavaScript only replaces the first occurrence.
is that just the regex for \ or is there another escape char in there that I can't see. It works fine but would like to understand why
that is the world's greatest link! I've been looking for something like this forever.
@Dave - The ` \ ` is just to escape the ` / `, is that what you mean? I'm unclear on your comment.
Pretty much. I was thinking the // was / escaped.
3

You can use the following trick:

str = str.split("/").join("\\");

More generally:

function replaceAll(str, a, b) {
    return str.split(a).join(b);
}

This avoids regular expression nightmares.

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.