Compare char to other chars in javascript

4

In my answer, I have this code:

s.match(/[AEIOU]/)

This seems too verbose to check if a string is one of A, E, I, O, or U.

I tried:

"AEIOU".includes(s)

But that's 1 byte longer. Can I do this in a shorter way?

ABot

Posted 2017-07-20T21:07:03.393

Reputation: 203

5Before anyone close-votes this, this is a valid tips question. – HyperNeutrino – 2017-07-20T21:08:03.610

I don't think so ... – Zacharý – 2017-07-20T21:09:34.997

1~"AEIOU".indexOf(s) also works. – Stephen – 2017-07-20T21:14:43.787

@CloseVoter(s) how is this too broad? It's asking for golfing advice for a specific snippet. – programmer5000 – 2017-07-20T21:41:25.403

Answers

5

Try /[AEIOU]/.test(s)

Body must be at least 30 characters; you entered 21

HyperNeutrino

Posted 2017-07-20T21:07:03.393

Reputation: 26 575

That's a great way around the character minimum. I almost didn't notice it. – Fabian Röling – 2017-08-22T17:22:32.500

4

If s is a literal and not a variable, you can do the following:

/[AEIOU]/.test`A`
"AEIOU".includes`A`
~"AEIOU".indexOf`A`

which is shorter than

/[AEIOU]/.test("A")
"AEIOU".includes("A")
~"AEIOU".indexOf("A")

Stephen

Posted 2017-07-20T21:07:03.393

Reputation: 12 293

Though if it's one of the former the result is deterministic and you can golf it down to one byte 1 and 0 – Downgoat – 2017-07-21T04:23:22.510

@Downgoat I was mostly sharing the backticks trick - usually this would be used with "AEIOU" is not a constant, so s.includes<backtick>A<backtick> – Stephen – 2017-07-21T11:30:34.143

The backticks trick isn't relevant here... – ASCII-only – 2018-04-25T07:08:43.677

2

s.match`[AEIOU]` goes well.....

l4m2

Posted 2017-07-20T21:07:03.393

Reputation: 5 985

That doesn't work... – ASCII-only – 2018-04-25T07:10:56.350

1@ASCII-only, it works, just l4m2 had to pay the price of not using code block markup. – manatwork – 2018-04-25T08:08:24.323

@manatwork ah, I see – ASCII-only – 2018-04-25T08:08:48.903