How to check if a string contains only letters, numbers, underscores and dashes in Node.js

1 Answer

0 votes
function isValidString(s) {
    const pattern = /^[A-Za-z0-9_-]*$/;
    return pattern.test(s);
}

// Export function for use in other modules
module.exports = { isValidString };

// Example usage
if (require.main === module) {
    const s1 = "-abc_123-";
    console.log(isValidString(s1) ? "yes" : "no");

    const s2 = "-abc_123-(!)";
    console.log(isValidString(s2) ? "yes" : "no");
}

  
  
/*
run:
      
yes
no

*/
 

 



answered May 31, 2025 by avibootz
...