Raz Buchnik
Raz Buchnik

Reputation: 8401

JS RegExp how to NOT ALLOW special chars AND numbers?

I have a good RegExp which does not allow numbers at all:

/^[\D]*$/

Now I just need that it also will not be able to prevent special chars like:

!@#$%^&*()_+-/."'<>\|±§`

and etc (if there more special chars which I don't know - I will be glad to block them too).

This does work - but it's probably won't cover all cases:

/^[^\d^!^@^#^$^%^&^*^(^)^[^\]^{^}^;^:^|^,^<^>^.^?^/^\\^~^`^±^§]*$/

Upvotes: 2

Views: 555

Answers (1)

Sweeper
Sweeper

Reputation: 270945

You need to use a version of Javascript that supports regex with full Unicode (i.e. ES 6+). Then you can use a regex like this:

/^\p{L}*$/gu

This only allows characters present in the L unicode character class, which stands for "Letters".

var regex = /^\p{L}*$/gu;
console.log("abc".match(regex));
console.log("αβγ".match(regex));
console.log("абв".match(regex));
console.log("ひらがな".match(regex));
console.log("中文".match(regex));
console.log("!@#$".match(regex));
console.log("1234abc".match(regex));

Upvotes: 2

Related Questions