javascript

Return "True" if all the characters in a string are "x" or "X" else return false


I am looking at this code challenge:

Complete the function isAllX to determine if the entire string is made of lower-case x or upper-case X. Return true if they are, false if not.

Examples:

isAllX("Xx"); // true
isAllX("xAbX"); // false

Below is my answer, but it is wrong. I want "false" for the complete string if any of the character is not "x" or "X":

function isAllX(string) {
  for (let i = 0; i < string.length; i++) {
    if (string[i] === "x" || string[i] === "X") {
      console.log(true);
    } else if (string[i] !== "x" || string[i] !== "X") {
      console.log(false);
    }
  }
}

isAllX("xAbX");


Solution

  • Without any method if you want

     function isAllX(str) {
      let flag = true;
      for (let i = 0; i < str.length; i++) {
        if (str[i] !== "x" && str[i] !== "X") {
          flag = false;
          // break;
        }
      }
      return flag;
    }
    
    console.log(isAllX("xAbX"));
    console.log(isAllX("XXXxxxXXXxxx"));
    console.log(isAllX("xx"));