Pregunta

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]) { ...
¿Fue útil?

Solución

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. */
}

Otros consejos

You can do it with a regular expression:

var theChar = str.charAt(i);
if (/[.,#$;:]/.test(theChar)) {
  // ...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top