-1

I am trying get directory name with backslash, but I am getting this DirectoryFolder. Can't figure out how to match backslah \ as well.

DirPath = "Directory\Folder"

val = DirPath.match(/(\w+)/)[1];

The result I want is this

Directory\Folder

Maantje
  • 1,781
  • 2
  • 20
  • 33
  • 1
    Could you give us some more input of what should and what should not match? – Lucas Araujo May 19 '16 at 20:09
  • it should match "Directory\Folder". I am extracting this info a text file. The test might look like this. "This is your home folder Directory\Folder.... – azad aawaraa May 19 '16 at 20:52
  • The string should be `var DirPath = "Directory\\Folder"`, otherwise the ``\`` will be left out, missing, in the string. Then, `DirPath.match(/\w+/)[0]` will work. – Wiktor Stribiżew May 20 '16 at 18:22

3 Answers3

0

My regex isn't the best but this might work.

([A-Z\\])\w+
Maantje
  • 1,781
  • 2
  • 20
  • 33
0

If I understand your question correctly, you need to know how to match a backslash, correct?

If that is the case, you can escape your backslash

The final regex would look like /(\w|\\)+/

jay
  • 177
  • 1
  • 12
  • Correct, I tried your code. Still don't work. It return data without backslash. DirectoryFolder, but I want it to return Directory\Folder – azad aawaraa May 19 '16 at 20:21
  • @azadaawaraa , when I run your code, it looks like the \ in DirPath is trying to escape the `F` in Folder. When I change it to `DirPath = "Directory\\Folder";` it matches. Are you defining DirPath manually, or are you getting it from somewhere already defined? – jay May 19 '16 at 20:30
  • I am getting it from other place. So, I cannot change it to "Directory\\Folder". It has to stay as "Directory\Folder". I am extracting the "Directory\Folder" from string of text file. – azad aawaraa May 19 '16 at 20:47
  • Can you post how you are getting it from the text file? And how is that text file being populated? Is it possible that the \ isn't being escaped before it is stored to the text file? – jay May 19 '16 at 21:04
0

Can you use ES6? If so you can use the String.raw() static method:

var DirPath = String.raw`Directory\Folder`;

var re = /[\w\\]+/;

document.body.textContent = DirPath.match(re);
timolawl
  • 5,434
  • 13
  • 29