6

I'm new to nodejs.
Can anyone tell me how to replace all '\' to '/' ? Thanks.

my code:console.log(process.cwd());
result:e:\Workspace\WebStorm\Ren\LittleCase

I have tried the following methods:

console.log(process.cwd().replace('\\','/'));

However, only the first to be successfully replaced.like this:

e:/Workspace\WebStorm\Ren\LittleCase  
BERARM
  • 247
  • 1
  • 6
  • 14

3 Answers3

13

You're really close!

The problem is that Javascript doesn't match more then once. But don't worry! You can use a RegExp!

To make a regex, just replace the quotes with backslashes: /\\/. That will match \

Sadly, that will only match once, so you can add the global flag g to the end: /\\/g.

So, with your example, that would be:

console.log(process.cwd().replace(/\\/g,'/'));
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
3

Replace only replaces the first instance; however, if you turn it into a regular expression with a global modifier, it will replace all instances.

var regex = /\\/g;
process.cwd().replace(regex, '/');

There are some other, but less orthodox (i.e. less readable to future programmers) methods: https://stackoverflow.com/a/17606289/703229

Community
  • 1
  • 1
Sam
  • 20,096
  • 2
  • 45
  • 71
1

You have to use a regexp to replace more than one occurence

.replace(/\\/g,'/')
user3
  • 740
  • 3
  • 15