1

I need to use a regex result as well as its fail reason. Consider following:

myStr = "loremipsum5lorem"; 
function check(x) {
    x = /^[a-zA-Z]$/.test(x); 
    console.log(x, reason); 
}; 
console.log(check(myStr)); 

Should output something like this:

false, non-alphanumeric character at index 11

How can I get the reason?

ceremcem
  • 3,900
  • 4
  • 28
  • 66
  • 1
    In this case your regex fails, because there is more than one character in your string (or because you missed a `+` or `*` in your regex). – Sebastian Proske Jun 18 '16 at 16:44
  • To the best of my knowledge this is impossible not only in javascript but in all regexp implementations in all languages including C, Java, C++, Go, Tcl, Perl, Python, Ruby, Scala, Basic, Pascal, Rust, Lisp, awk, sed, etc.. – slebetman Jun 18 '16 at 16:45
  • @slebetman Should be possible using `RegExp` `[^a-zA-Z]` , `.index` property of `String.prototype.match()` – guest271314 Jun 18 '16 at 17:05
  • 1
    You can inversely find where a regexp giving what must **not** match "failed", by something like `"loremipsum5lorem".search(/[^a-zA-Z]/)`. –  Jun 18 '16 at 17:21

1 Answers1

1

You can use a for loop to check each character of input string

myStr = "loremipsum5lorem"; 
function check(str) {
    var x = /^[a-zA-Z]$/, reason;
   // console.log(x, reason); 
   for (var i = 0; i < str.length; i++) {
     if (!x.test(str[i])) {
       reason = "false, character at " + i + " is " + str[i];
       break;
     }
   }
   return reason ? reason : "all characters are /^[a-zA-Z]$/"
}; 
console.log(check(myStr)); 

alternatively using RegExp /[^a-zA-Z]/, String.prototype.match(), .index property of .match()

myStr = "loremipsum5lorem"; 
function check(str) {
    var x = /[^a-zA-Z]/, reason;
    var match = str.match(x);
    if (match) reason = "false, character at " + match.index + " is not a-zA-Z";
    return match ? reason : true
}; 
console.log(check(myStr));

As pointed out by @torazaburo, String.prototype.search() could also be utilized

myStr = "loremipsum5lorem"; 
function check(str) {
    var x = /[^a-zA-Z]/, reason;
    var match = str.search(x);
    if (match > -1) reason = match;
    return reason ? "character that is not a-zA-Z found at " + reason : true
}; 

console.log(check(myStr));
guest271314
  • 1
  • 15
  • 104
  • 177