WHITECOLOR
WHITECOLOR

Reputation: 26142

Javascript regex: test if text contains only characters from a set

How it is better to check (test) if text contains only characters from set (for example if text contains only punctuation marks)

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

res = text.replace(regex, '')

if (res) return false

so I made it with replace is it possible to do it with regex.test?

Upvotes: 2

Views: 1354

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

Yes it is. There are two possibilities. One is, that you use anchors to assert that the full string is made up of these:

var regex = /^[\.,-\/#!$%\^&\*;:{}=\-_`~()]+$/;
if(regex.test(text))

Alternatively you can use a negated character class and see whether it matches and then again negate the result

var regex = /[^\.,-\/#!$%\^&\*;:{}=\-_`~()]/;
if(!regex.test(text))

Note that ,-\/ is a range that includes ,-./. This is redundant and may become a source of errors if the character class is ever changed. You might want to simplify your character class to:

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

(Or the negated version of that, depending on which approach you choose.)

Upvotes: 8

Related Questions