RegEx for Javascript to allow only alphanumeric

前端 未结 18 1536
轻奢々
轻奢々 2020-11-22 15:13

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just w

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:39

    Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.

    /[^a-z\d]/i    
    

    Here is an example:

    var alphanumeric = "someStringHere";
    var myRegEx  = /[^a-z\d]/i;
    var isValid = !(myRegEx.test(alphanumeric));
    

    Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.

提交回复
热议问题