RegEx for Javascript to allow only alphanumeric

前端 未结 18 1278
轻奢々
轻奢々 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:47

    If you wanted to return a replaced result, then this would work:

    var a = 'Test123*** TEST';
    var b = a.replace(/[^a-z0-9]/gi,'');
    console.log(b);
    

    This would return:

    Test123TEST
    

    Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".

    WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".

提交回复
热议问题