Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript test string for only letters and numbers [duplicate]

I have the following functions

JavaScript

function lettersNumbersOnly(string){
   if (/[A-Za-z0-9]/.test(string)) {
     console.log('Clean');
   }else{
     console.log('Not Matching');
   }
}

$(".test-input").change(function(){
  lettersNumbersOnly($(this).val());
});

If I were to put letters and numbers into that .test-input field, I get the "Clean". BUT if I put characters like !2@$% etc. I still get the "Clean" which is not what I want. I just want strictly letters and numbers. Any suggestions?

like image 387
Taylor Foster Avatar asked Sep 11 '26 23:09

Taylor Foster


1 Answers

Use start and end anchors for complete string match and + for one or more repetition of character class.

if (/^[A-Za-z0-9]+$/.test(string)) 
like image 123
Pranav C Balan Avatar answered Sep 14 '26 12:09

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!