开发者

Is it possible to compare a char to regexp?

开发者 https://www.devze.com 2023-03-24 03:10 出处:网络
I want to check if a single character matches a set of possible other characters so I\'m trying 开发者_JAVA技巧to do something like this:

I want to check if a single character matches a set of possible other characters so I'm trying 开发者_JAVA技巧to do something like this:

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

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


Use test

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


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消