if charAt equal to a list of characters

lbutlr picture lbutlr · Jan 27, 2014 · Viewed 7.2k times · Source

I want something like the following in Javascript

if str.charAt(index) (is in the set of) {".", ",", "#", "$", ";", ":"}

Yes, I know this must be simple, but I can't seem to get the syntax right. What I have now is

theChar = str.charAt(i);
if ((theChar === '.') || (theChar === ',') || (theChar === ... )) {
  // do stuff
}

This works, but there must be a better way.

Edit: I did this, but not sure if it's GOOD or not:

var punc = {
    ".":true,
    ",":true,
    ";":true,
    ":":true
};

if (punc[str.charAt[index]) { ...

Answer

user1620696 picture user1620696 · Jan 27, 2014

Define an array with those chars and simply search in the array. One way to do that is the following:

var charsToSearch = [".", ",", "#", "$", ";", ":"];
var theChar = str.charAt(i); /* Wherever str and i comes from */

if (charsToSearch.indexOf(theChar) != -1) {
    /* Code here, the char has been found. */
}