2

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
  • 60,628
  • 22
  • 121
  • 123
ilyo
  • 35,851
  • 46
  • 106
  • 159

3 Answers3

5

Use test

/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/.test(str.charAt(0))
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
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
  • 139,544
  • 27
  • 275
  • 264
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
  • 135,331
  • 41
  • 252
  • 292