Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if charAt equal to a list of characters

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]) { ...
like image 614
lbutlr Avatar asked Mar 20 '23 19:03

lbutlr


1 Answers

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. */
}
like image 116
user1620696 Avatar answered Apr 19 '23 11:04

user1620696