RegEx for Javascript to allow only alphanumeric

2019-01-01 04:35发布

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 want one what would allow either and not require both.

12条回答
骚的不知所云
2楼-- · 2019-01-01 05:16

It seems like many users have noticed this these regular expressions will almost certainly fail unless we are strictly working in English. But I think there is an easy way forward that would not be so limited.

  1. make a copy of your string in all UPPERCASE
  2. make a second copy in all lowercase

Any characters that match in those strings are definitely not alphabetic in nature.

let copy1 = originalString.toUpperCase();
let copy2 = originalString.toLowerCase();
for(let i=0; i<originalString.length; i++) {
    let bIsAlphabetic = (copy1[i] != copy2[i]);
}

Optionally, you can also detect numerics by just looking for digits 0 to 9.

查看更多
呛了眼睛熬了心
3楼-- · 2019-01-01 05:18

Extend the string prototype to use throughout your project

    String.prototype.alphaNumeric = function() {
        return this.replace(/[^a-z0-9]/gi,'');
    }

Usage:

    "I don't know what to say?".alphaNumeric();
    //Idontknowwhattosay
查看更多
与风俱净
4楼-- · 2019-01-01 05:18

Even better than Gayan Dissanayake pointed out.

/^[-\w\s]+$/

Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$

You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.

查看更多
听够珍惜
5楼-- · 2019-01-01 05:20
/^([a-zA-Z0-9 _-]+)$/

the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.

查看更多
明月照影归
6楼-- · 2019-01-01 05:23

Input these code to your SCRATCHPAD and see the action.

var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
查看更多
临风纵饮
7楼-- · 2019-01-01 05:25

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".

查看更多
登录 后发表回答