rajmalhotraml
rajmalhotraml

Reputation: 313

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.

Upvotes: 1

Views: 94

Answers (2)

Bergi
Bergi

Reputation: 664327

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");
    }
}

Upvotes: 2

Joseph Myers
Joseph Myers

Reputation: 6552

Your expr variable is still just a string (validationvalues.split("|")[0] will return a string). That's the reason it does not work as a regular expression.

You need to add a line after the initial definition of expr.

expr = new RegExp(expr, 'i');

The 'i' is just an example of how you would use a case-insensitive flag or other flags. Use an empty string if you want a case-sensitive search (the default).

Also, you need to take out the / and / which are surrounding your first pattern. They are only needed when using regular expression literals in JavaScript code, and are not needed when converting strings into regular expressions.

Upvotes: 1

Related Questions