Search code examples
javascriptregexconditional-statementsalphanumericnon-alphanumeric

Use IF operator to diverge actions on alphanumeric and non-alphanumeric elements in a given array


I need help working on arrays that can contain both ALPHANUMERIC and NON-ALPHANUMERIC elements.

I need to perform an action for ALPHANUMERIC, and a different action for NON-ALPHANUMERIC.

I have been trying different ways to declare the statement If to diverge the two options, but I don't come up with the right formula.

The closest solution I can get is too dirty, I just tell the program the element has to be different from " " and diferent from "!" and different from "?". Not a clean solution. Could someone help? Maybe using a RegEx Expression?

  var myArray=["H","O","W"," ","A","R","E"," ","U","?"];
  var i=0;


  while(i<myArray.length){

  if(myArray[i]!=" " && myArray[i]!="!"&& myArray[i]!="?"&& myArray[i]!="."){
  //PERFORM ACTION 1 Example:
  return: "Hello";
  }


  else{
  //PERFORM ACTION 2 Example:
  return: "Goodbye";
  }

  i++;
  }

I have tried with the following Regex, and not succeded:

if(myArray[i]!=[A-Za-z0-9_])

and also:

if(myArray[i]!=/\W/g)

None of them work :( Help, please.

Thank you.


Solution

  • SOLUTION:

    var myArray=["H","O","W"," ","A","R","E"," ","U","?"];
    var i=0;
    var alphaChecker = new RegExp("^[a-zA-Z0-9_]*$");
    
    
    
    while(i<myArray.length){
    
    if(alphaChecker.test(myArray[i])){
    //PERFORM ACTION 1 Example:
    myArray[i]= "Hello";
    }
    
    
    else{
    //PERFORM ACTION 2 Example:
    myArray[i]= "Goodbye";
    }
    
    i++;
    }
    
    return myArray;
    

    This works well.