4

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]) { ...
lbutlr
  • 326
  • 3
  • 15

2 Answers2

5

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. */
}
user1620696
  • 9,035
  • 12
  • 42
  • 76
  • @L105 are you sure about that? – Pointy Jan 27 '14 at 15:03
  • Going to make a jsPerf. – L105 Jan 27 '14 at 15:04
  • While you're at it, make one using `String.indexOf` as well, e.g. `".,#$;:".indexOf(theChar) !== -1`. Although I don't think performance will matter much for this snippet. – Mattias Buelens Jan 27 '14 at 15:07
  • [In my test](http://jsperf.com/indexof-vs-regex-m5) the String `indexOf` is fastest in Firefox, followed by the regex and then the array. It's the opposite in Chrome. – Pointy Jan 27 '14 at 15:15
  • In my test, regex is 59% slower in chrome. http://jsperf.com/regexndexof, second time : 9% slower. – L105 Jan 27 '14 at 15:16
  • All of these work, but I am actaully sticking with the solution I came up with for this instance just because I really like the syntax `if (punc[str.charAt[index]) { ... }` even though it's a bit wordy in creating the set in the first place. – lbutlr Jan 28 '14 at 15:20
2

You can do it with a regular expression:

var theChar = str.charAt(i);
if (/[.,#$;:]/.test(theChar)) {
  // ...
}
Pointy
  • 371,531
  • 55
  • 528
  • 584
  • Not very friendly for new JavaScript programmers, but I guess it's good to demonstrate a *practical* solution. – Mattias Buelens Jan 27 '14 at 15:02
  • @MattiasBuelens I guess it depends on where the new JavaScript programmer comes from :) By the time I learned JavaScript, I'd known about regular expressions for a long time. – Pointy Jan 27 '14 at 15:03
  • ah, that's what I was trying to do, but ten I got distracted by sets. – lbutlr Jan 27 '14 at 15:29