Reputation: 150
I'm attempting to write a function that takes in a string of any number of characters, and validates that the string contains only a predefined set of characters (none to many of each of those four characters).
validRna(strand) {
var checkStrand = strand.match(/^(CGAT)$/g)
return checkStrand == strand
}
Currently what I have will only match to the first character and not the whole string. I'm trying to understand both the best method to check with, and how to build the Regex (always struggled with regular expressions).
Upvotes: 0
Views: 304
Reputation: 3873
You could use a regex pattern such as /^[CAGT]*$/
and the test()
method to check each string.
[]
will match any character within that set and *
means 0 or more of those characters. So this essentially says from the start: ^
to the end $
there must be 0 or more of C or A or G or Ts.
console.log(/^[CAGT]*$/.test("GAFASF"));
console.log(/^[CAGT]*$/.test("CAGTGAGA"));
console.log(/^[CAGT]*$/.test("GGATCAGCTTGA"));
validRna(strand) {
return /^[CAGT]*$/.test(strand);
}
Upvotes: 3