// Function to check if a string is alphanumeric
function isAlphaNumeric(str) {
// Using regular expression to check for alphanumeric characters
return /^[a-zA-Z0-9]+$/.test(str);
}
// Example usage
console.log("Is 'hello123' alphanumeric?", isAlphaNumeric("hello123"));
console.log("Is '123' alphanumeric?", isAlphaNumeric("123"));
console.log("Is 'hello 123' alphanumeric?", isAlphaNumeric("hello 123"));
console.log("Is 'hello@123' alphanumeric?", isAlphaNumeric("hello@123"));
// Function to check if a string is alphanumeric
function isAlphaNumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}
// Alternative function using case-insensitive flag
function isAlphaNumericAlt(str) {
return /^[a-z0-9]+$/i.test(str);
}
// Example usage
console.log("Using first function:");
console.log("Is 'Hello123' alphanumeric?", isAlphaNumeric("Hello123"));
console.log("Is 'HELLO123' alphanumeric?", isAlphaNumeric("HELLO123"));
console.log("\nUsing alternative function with case-insensitive flag:");
console.log("Is 'Hello123' alphanumeric?", isAlphaNumericAlt("Hello123"));
console.log("Is 'HELLO123' alphanumeric?", isAlphaNumericAlt("HELLO123"));
ファイルを保存し、再度以下のコマンドで実行します。
node alphanumeric.js
以下の出力が表示されるはずです。
Using first function:
Is 'Hello123' alphanumeric? true
Is 'HELLO123' alphanumeric? true
Using alternative function with case-insensitive flag:
Is 'Hello123' alphanumeric? true
Is 'HELLO123' alphanumeric? true
代替関数では、正規表現の末尾に i フラグを使用しています。これにより、パターンマッチングが大文字小文字を区別しなくなります。つまり、文字クラスに a - z のみを含めれば、自動的に大文字もマッチするようになります。
const readline = require("readline");
// Create a readline interface for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to check if a string is alphanumeric
function isAlphaNumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}
// Function to check the input
function checkInput(input) {
if (isAlphaNumeric(input)) {
console.log(`"${input}" is alphanumeric.`);
} else {
console.log(`"${input}" is NOT alphanumeric.`);
console.log(
"Alphanumeric strings contain only letters (A-Z, a-z) and numbers (0-9)."
);
}
// Ask if the user wants to check another string
rl.question("\nDo you want to check another string? (yes/no): ", (answer) => {
if (answer.toLowerCase() === "yes" || answer.toLowerCase() === "y") {
askForInput();
} else {
console.log("Thank you for using the alphanumeric validator!");
rl.close();
}
});
}
// Function to ask for input
function askForInput() {
rl.question("Enter a string to check if it is alphanumeric: ", (input) => {
checkInput(input);
});
}
// Welcome message
console.log("=== Alphanumeric String Validator ===");
console.log(
"This tool checks if a string contains only alphanumeric characters (A-Z, a-z, 0-9).\n"
);
// Start the program
askForInput();