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
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,'/'));
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
You have to use a regexp to replace more than one occurence
.replace(/\\/g,'/')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With