1

I want to check if a single character matches a set of possible other characters so I'm trying to do something like this:

str.charAt(0) == /[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/

since it doesn't work is there a right way to do it?

sblundy
  • 59,536
  • 22
  • 119
  • 123
ilyo
  • 34,891
  • 42
  • 103
  • 154

3 Answers3

4

Use test

/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/.test(str.charAt(0))
Ray Toal
  • 82,964
  • 16
  • 166
  • 221
2

Yes, use:

if(str.charAt(0).match(/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/))

charAt just returns a one character long string, there is no char type in Javascript, so you can use the regular string functions on it to match against a regex.

Paul
  • 135,475
  • 25
  • 268
  • 257
1

Another option, which is viable as long as you are not using ranges:

var chars = "[].,-/#!$%^&*;:{}=-_`~()";

var str = '.abc';
var c = str.charAt(0);

var found = chars.indexOf(c) > 1;

Example: http://jsbin.com/esavam

Another option is keeping the characters in an array (for example, using chars.split('')), and checking if the character is there:

How do I check if an array includes an object in JavaScript?

Community
  • 1
  • 1
Kobi
  • 130,553
  • 41
  • 252
  • 283