1

I am trying to remove __dirname from a directory I need to copy (recursively). I gather information about the problem:

console.log(typeof __dirname); // string
console.log(__dirname); // c:\test

I need to create the regex from a string I get from the program. Therefore I must use RegExp(myString). I do a reality check on jsfiddle to make sure the right way to escape \ is with \/ fiddle.

I run the code in the browser and it works. I run the code in node.js and it does not work. I take this to the extreme by trying to remove RegExp(__dirname) from __dirname.

If you have a string var s = __dirname.toString() + "myOtherPath/a.cat" how do you remove the __dirname part of the string from s?

user1873073
  • 3,580
  • 5
  • 46
  • 81

1 Answers1

1

Your regex example is wrong. The regex is for removing backslash. But the string itself does not have either backslash or slash.

var y = "c:\y";
//"c:y"

To correctly add backslash you have to

var y = "c:\\y";
//"c:\y"

Your example would have worked in linux where the separator is /, which does not need to be escaped. Besides it looks like you are doing substring replace not regex replace. So simply giving the __dirname in replace would suffice :

var y = __dirname;
var z = y.replace(__dirname,"").toString();
user568109
  • 47,225
  • 17
  • 99
  • 123