0

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.

jordivilagut
  • 333
  • 2
  • 9
  • 1
    Are you iterating over array? If yes, add complete code, if not, you need to. – Tushar Jan 18 '16 at 05:55
  • 1
    To check alphanumeric characters, use regex `/^[a-zA-Z0-9]+$/` with `test()`. – Tushar Jan 18 '16 at 05:56
  • 1
    `ARRAY[i]` can not have all the values mentioned in the conditions. You should be using `||` instead.. – Rayon Jan 18 '16 at 05:58
  • Actually, `ARRAY[i]` can ***not*** be all those values. How about fixing the obvious syntax errors first, like the missing comma in the array – adeneo Jan 18 '16 at 06:00
  • `if ( [" ", "!", "."].indexOf(myArray[i]) === -1 ) return "Hello";` – adeneo Jan 18 '16 at 06:05
  • My code is able to sort out space, exclamation mark, question mark, and dot. Now I want to find a expression that sorts out anything that is not a letter. If it's a letter say Hello (example action), if it's something else (space, question mark, etc), say Goodbye. – jordivilagut Jan 18 '16 at 06:09
  • Possible duplicate of [Check whether a string matches a regex](http://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex) – Gavriel Jan 18 '16 at 06:34

1 Answers1

0

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.

jordivilagut
  • 333
  • 2
  • 9