How to check is string has both letter and number in javascript

Viewed 45

I have string "JHJK34GHJ456HJK". How to check if this string has both letter and number, doesn't have whitespace, doesn't have special characters like # - /, If has only letter or only number didn't match.

I try with regex below, result is true if string is only number or letter.

const queryLetterNumber = /^[A-Za-z0-9]*$/.test("JHJK34GHJ456HJK");
2 Answers

const input= [
  'JHJK34GHJ456HJK',
  'JHJKAAGHJAAAHJK',
  '123456789012345',
  'JHJK34 space JK',
  'JHJK34$dollarJK'
];
const regex = /^(?=.*[0-9])(?=.*[A-Za-z])[A-Za-z0-9]+$/;
input.forEach(str => {
  console.log(str + ' => ' + regex.test(str));
});

Output:

JHJK34GHJ456HJK => true
JHJKAAGHJAAAHJK => false
123456789012345 => false
JHJK34 space JK => false
JHJK34$dollarJK => false

Explanation:

  • ^ - anchor at beginning
  • (?=.*[0-9]) - positive lookahead expecting at least one digit
  • (?=.*[A-Za-z]) - positive lookahead expecting at least one alpha char
  • [A-Za-z0-9]+ - expect 1+ alphanumeric chars
  • $ - anchor at end

you should use a regular expression to check for alphanumeric content in the string

/^[a-z0-9]+$/i

The above is a sample that checks for a-z and numbers from 0-9. however, review other options as given here

Related