Home > Software engineering >  How do I find if a string has only letters, numbers and underscore characters?
How do I find if a string has only letters, numbers and underscore characters?

Time:10-30

I want to check if my string has only letters, numbers or underscore in it. I have this code

const str = 'test'

for (let i = 0; i < str.length; i  ) {
  if (str.charAt(i) != /^(\w|_) $/) {
    return false
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

No matter what, it's always returning false although just introducing valid values.

Could anyone help?

Many thanks!

CodePudding user response:

Just use test() with the regex pattern ^\w :

var str = 'test_here_123';
if (/^\w $/.test(str)) {
    console.log("only letters, numbers, or underscore");
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

For reference, \w by definition matches letters, numbers, or underscore (which are collectively known as "word characters").

  • Related