How to check if a string contains only letters and numbers using RegEx in TypeScript

1 Answer

0 votes
function isAlphanumeric(str: string): boolean {
    // Define the regular expression for alphanumeric characters
    const alphanumericRegex: RegExp = /^[a-zA-Z0-9]+$/;

    // Use the test() method to check if the string matches the pattern
    return alphanumericRegex.test(str);
}

const str: string = "VuZ3q7J4wo35Pi";

if (isAlphanumeric(str)) {
    console.log("The string contains only letters and numbers.");
} else {
    console.log("The string contains characters other than letters and numbers.");
}

  
  
/*
run:
  
"The string contains only letters and numbers." 
  
*/

 



answered Mar 26, 2025 by avibootz
...