我有一个字符串“5A”或“a6”。我只想在结果上得到“A”或“a”。我正在使用以下内容,但它不起作用。
Javascript
var answer = '5A';
answer = answer.replace(/^[0-9]+$/i);
//console.log(answer) should be 'A';
最佳答案
let answer = '5A';
answer = answer.replace(/[^a-z]/gi, '');
// [^a-z] matches everything but a-z
// the flag `g` means it should match multiple occasions
// the flag `i` is in case sensitive which means that `A` and `a` is treated as the same character ( and `B,b`, `C,c` etc )
代替 a-z
那么你可以使用 \p{L}
和 /u
修饰符,它们将匹配任何字母,而不仅仅是a though z,例如:
'50Æ'.replace(/[^\p{L}]/gu, ''); // Æ
// [^\p{L}] matches everything but a unicode letter, this includes lower and uppercase letters
// the flag `g` means it should match multiple occasions
// the flag `u` will enable the support for unicode character classes.
参见 https://caniuse.com/mdn-javascript_builtins_regexp_unicode寻求支持
关于javascript - 如何仅从字母数字字符串中提取字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624457/