if charAt equal to a list of characters
Asked Answered
S

2

5

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]) { ...
Steffi answered 27/1, 2014 at 14:57 Comment(0)
I
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. */
}
Incursion answered 27/1, 2014 at 15:1 Comment(6)
@L105 are you sure about that?Phalange
Going to make a jsPerf.Hy
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.Chanson
In my test the String indexOf is fastest in Firefox, followed by the regex and then the array. It's the opposite in Chrome.Phalange
In my test, regex is 59% slower in chrome. jsperf.com/regexndexof, second time : 9% slower.Hy
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.Steffi
P
2

You can do it with a regular expression:

var theChar = str.charAt(i);
if (/[.,#$;:]/.test(theChar)) {
  // ...
}
Phalange answered 27/1, 2014 at 15:1 Comment(3)
Not very friendly for new JavaScript programmers, but I guess it's good to demonstrate a practical solution.Chanson
@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.Phalange
ah, that's what I was trying to do, but ten I got distracted by sets.Steffi

© 2022 - 2024 — McMap. All rights reserved.