-1

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");
Ivar
  • 6,138
  • 12
  • 49
  • 61
Ismeet
  • 419
  • 5
  • 19
  • Have you made any attempts? – epascarello Sep 14 '22 at 12:38
  • What did you try? Where are you stuck? Stack Overflow is not a place where you can just "dump" a problem and expect someone to write everything for you. – Cerbrus Sep 14 '22 at 12:38
  • I update qustion. – Ismeet Sep 14 '22 at 12:39
  • [Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters](https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a). Use the first one in the accepted answer and just remove the `{8,}` part. (Or replace it with whatever you need the length to be.) – Ivar Sep 14 '22 at 12:44
  • const string = "QW23RLRK45r"; const chek = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?!.* ).{4,16}$/.test(le); It is false. – Ismeet Sep 14 '22 at 12:52
  • The regex for `Contains` is: `/^(?=.*[A-Za-z])/` for letters, you figure out for numbers. – Poul Bak Sep 14 '22 at 12:52
  • @Ismeet That is not the first regex of the accepted answer. I was referring to `"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"`. – Ivar Sep 14 '22 at 12:55
  • const le = "QW23RLRK45"; const q = /(^.*[A-Za-z])(^.*[0-9])/.test(le); It is false. – Ismeet Sep 14 '22 at 12:55
  • Please see the changed comment, it should work now. – Poul Bak Sep 14 '22 at 12:57
  • @Ivar it works /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]/ – Ismeet Sep 14 '22 at 13:02

2 Answers2

1

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
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20
-1

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

Saravanan
  • 7,637
  • 5
  • 41
  • 72
Nikita
  • 16
  • 2