Q:

regular expression javascript returning unexpected results

In the below code, I want to validate messageText with first validationPattern and display the corresponding message from the validationPatterns array.  Pattern and Message are separated by Pipe "|" character.
for this I am using the below code and always getting wrong result.  Can some one look at this and help me?
var messageText = "Message1234";
var validationPatterns = [
    ['\/^.{6,7}$/|message one'],
    ['\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|message two']
];
for (var i = 0; i < validationPatterns.length; i++) {
    var validationvalues = validationPatterns[i].toString();

    var expr = validationvalues.split("|")[0];
    console.log(expr.constructor);

    if(expr.test(messageText)) {
       console.log("yes");
    } else {
       console.log("no");
    }
}

I know that we cannot use pipe as separator as pipe is also part of regular expression.  However I will change that later.

A:

Your validationpatterns are strings. That means:

The backslashes get eaten as they just string-escape the following characters. "\b" is equivalent to "b". You would need to double escape them: "\\b"
You cannot call the test method on them. You would need to construct RegExp objects out of them.

While it's possible to fix this, it would be better if you just used regex literals and separated them from the message as distinct properties of an object (or in an array).
var inputText = "Message1234";
var validationPatterns = [
    [/^.{6,7}$/, 'message one'],
    [/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/, 'message two']
];
for (var i = 0; i < validationPatterns.length; i++) {
    var expr = validationPatterns[i][0],
        message = validationPatterns[i][1];
    console.log(expr.constructor); // RegExp now, not String

    if(expr.test(inputText)) {
       console.log(message+": yes");
    } else {
       console.log(message+": no");
    }
}

