rabbitwerks
rabbitwerks

Reputation: 355

How can I check if a string only contains certain letters, and if it has others, it returns false

I am trying to take in the value of an input:text field, then check to see if that string has only valid characters. Valid characters being "G, C, T, A". I am trying to write validation for the string so that if it has invalid letters, it kicks it back to the user and asks for only valid letters.

How would I check against only certain characters in a string?

let rnaTransResult;
let validLetters = ["G", "C", "T", "A"];

runBtn.addEventListener('click', function(){
  let dna = userInput.value.toUpperCase();

  rnaTranscribe(dna);

  result.textContent = rnaTransResult;
});

function rnaTranscribe(dna){
  let dnaArray = dna.split('');

  for(let x = 0; x < dnaArray.length; x++){

    if(dnaArray[x] != validLetters[x]){
      console.log("invalid letters");
      return false;
    } else {
      for(let i = 0; i < dnaArray.length; i++){
        if(dnaArray[i] === "G"){
         // console.log("G swap for C");
          dnaArray[i] = "C";
        }  
      }
      console.log("end result: " + dnaArray);
      rnaTransResult = dnaArray.join('');
      console.log("Transcription complete - Result: " + rnaTransResult);
    }
 };

}

I have tried a few different methods without anything working. I am at a loss at the moment and would love to understand the concept thinking behind approaching this. Thank you in advance!

Upvotes: 1

Views: 1445

Answers (3)

R&#233;gis B.
R&#233;gis B.

Reputation: 189

You could also achieve this using regex.

[^GCTA]

Will match anything that isn't in your allowed characters,so you can do:

if(dnaArray.match(/[^GCTA]/)){//if dnaArray contains anything that isn't G,T,C,A
  ...
}

Upvotes: 3

chevybow
chevybow

Reputation: 11868

As a very naive solution: Loop through the length of the string and compare it to see if the array includes the value at the current index. There are better ways of doing this but this should clearly show what is going on and the logic behind it

let validLetters = ["G", "C", "T", "A"];

let dnaArray = "GCTATAB"

for(let x = 0; x < dnaArray.length; x++){
  if(!validLetters.includes(dnaArray[x])){
    console.log("invalid letter: " + dnaArray[x]);
   }

 }

Instead of console logging in your loop- you can set a boolean variable (initially to true- set it to false if there is an invalid letter in the loop then break). If the boolean is false- you know the string contains a letter that is not valid.

Upvotes: 0

cybersam
cybersam

Reputation: 66957

You can use the some function:

...
let letter = dnaArray[x];
if (validLetters.some(l => l === letter))
...

Upvotes: 2

Related Questions