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
}
}
No matter what, it's always returning false although just introducing valid values.
Could anyone help?
Many thanks!
Just use test() with the regex pattern ^\w+:
var str = 'test_here_123';
if (/^\w+$/.test(str)) {
console.log("only letters, numbers, or underscore");
}
For reference, \w by definition matches letters, numbers, or underscore (which are collectively known as "word characters").