Search code examples
javascriptstr-replace

changing file path model from Linux (/) to windows (\) in Java Script


I have some file paths in Unix system and I am trying to convert them to windows based path using java script Replace function.

For instance: I am trying to convert : //File/Test/images to \\File\Test\images

I am trying to achieve this by using string.replace which is

var winpath =oldPath.replace(/:|\\/g, "\/");

is this a correct way to replace the / to \?


Solution

  • Use a regex literal with the g modifier, and escape the "/" with a "\" so it doesn't clash with the delimiters.

    var myStr = '//File/Test/images', replacement = '';
    var replaced = myStr.replace(/\//g, replacement);