javascript - Validate the string which needs to match particular condition(Regular Expression)? -


i want validate string, should not contain special characters except underscore(_). have written below code not able through.

var string = 'pro$12'; var result = /[a-za-z0-9_]*/.test(string); 

in above given string not valid got result true. can body tell doing wrong here?

it returns true because, able match pro. can see actual matched string, match function, this.

console.log(string.match(/[a-za-z0-9_]*/)); # [ 'pro', index: 0, input: 'pro$12' ] 

even when doesn't match anything, example, input '$12', return true. because, * matches 0 or more characters. so, matches 0 characters before $ in $12. (thanks @jack pointing out)

so, need is

console.log(/^[a-za-z0-9_]*$/.test(string)); # false 

^ means beginning of string , $ means ending of string. telling regex engine that, match string has characters character class, beginning , ending of string.

note: instead of using explicit character class, [a-za-z0-9_], can use \w. same character class mentioned.

quoting mdn docs regexp,

\w

matches alphanumeric character basic latin alphabet, including underscore. equivalent [a-za-z0-9_].

for example, /\w/ matches 'a' in "apple," '5' in "$5.28," , '3' in "3d."

so, regex can shortened

console.log(/^\w*$/.test(string)); 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -