Tom
Tom

Reputation: 9643

match pattern not working

I'm trying to match strings that only have a, g, c or t in them (insensitive) so the string: "AAaaatCCCc" is valid while "catb" is not. this is my function:

var pattern = "/^[agct]+$/i";
if (!this.inputSeq.value.trim().match(pattern)){
    this.errMsg = "Invalid input sequence -must contain only a,g,c or t"
    updateErrorBox(this.errMsg);
}

When i enter valid strings i'm still getting the error message

Upvotes: 1

Views: 1604

Answers (2)

gdoron
gdoron

Reputation: 150263

Remove the quotes from the regex literal:

var pattern = "/^[agct]+$/i";

To:

var pattern = /^[agct]+$/i;

There is an implicitly conversion

regexp

A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

MDN

But it's not working, because you have flags in the pattern and slashes: /../.

var pattern = "^[agct]+$";
... .match(pattern)

Could work due the implicit conversion, but case sensitive because of the missing i flag.

Upvotes: 5

HBP
HBP

Reputation: 16043

Assuming your input text is being picked up correctly, a console log of its value might help isolate the issue, this code should work:

if (!this.inputSeq.value.match(/^\s*[agct]+\s*$/i)) {
    this.errMsg = "Invalid input sequence -must contain only a,g,c or t"
    updateErrorBox(this.errMsg);
}

You were using a literal sting instead of a regular expression for the pattern hence the error messages.

Upvotes: 1

Related Questions