Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all '\' to '/' in nodejs [duplicate]

Tags:

regex

node.js

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  
like image 613
BERARM Avatar asked Jul 19 '16 19:07

BERARM


3 Answers

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,'/'));
like image 114
Ben Aubin Avatar answered Sep 29 '22 18:09

Ben Aubin


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

like image 40
Sam Avatar answered Sep 29 '22 19:09

Sam


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

.replace(/\\/g,'/')
like image 34
user3 Avatar answered Sep 29 '22 19:09

user3