6

How do I check that?

I want to allow all A-Za-z0-9 , and underscore. Any other symbol, the function should return false.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

15

You can use a regular expression:

function isValid(str) { return /^\w+$/.test(str); }

\w is a character class that represents exactly what you want: [A-Za-z0-9_]. If you want the empty string to return true, change the + to a *.

To help you remember it, the \w is a word character. (It turns out that words have underscores in JavaScript land.)

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
1

I think this is a solution:

function check(input) {
  return /^\w+$/i.test(input);
}
ioseb
  • 16,625
  • 3
  • 33
  • 29