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");
CodePudding user response:
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
CodePudding user response:
Use String.prototype.match() in help