0
regularExpression = '[\w]:\\.*';

function validate() {
  debugger;

  var regex = new RegExp(regularExpression);
  var ctrl = document.getElementById('txtValue');

  if (regex.test(ctrl.value)) {
    return true;
  } else {
    return false;
  }
}

Above is my code with which I am validating a directory path being entered. Here is the link for validator website which shows the perfect match for C:\ or D:\ or D:\Abcd\List.odt. But when I try to run the above JavaScript it fails.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user2998990
  • 970
  • 5
  • 18
  • 36
  • @Tushar : can you he;p me with filepath reg ex. Same problem as above filepath reg ex : ^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$ – user2998990 Nov 27 '15 at 10:46

1 Answers1

4

When the Regular Expression string '[\w]:\\.*' is parsed by the JavaScript's RegEx engine, it will treat \w as an escaped character and since \w has no special meaning as an escaped character, it will treated as w only.

To fix this, you need to escape the \ like this

var regularExpression = '[\\w]:\\.*';

Or use RegEx literal like this

var regularExpression = /[\w]:\.*/;

As pointed out by Cyrbil in the comments, the character class [\w] is the same as \w only. So you can safely omit the square brackets around \w.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497