英文:
How to count unaccented English letters in Javascript?
问题
I'm trying to count the number of characters that are unaccented English letters in a string. For example, I would want the count to be 1 for the string "né!".
I thought I would be able to check if each character is in the range 'a'-'z' or 'A'-'Z', but that would include 'é':
'é' >= 'a' && 'é' <= 'z';
true
Both accented and unaccented letters seem to have the same code point:
"eé".codePointAt(0);
101
"eé".codePointAt(1);
101
I tried using regular expressions, but the string "né!" was treated like the 4-character string "né'!":
for (let i = 0; i < len; i++) {
var c = str.charAt(i);
if (re.test(c)) {
console.log("Is a letter: " + c);
numLetters++;
} else {
console.log("Is not a letter: " + c);
}
}
Output:
Is a letter: n
Is a letter: e
Is not a letter: ́
Is not a letter: !
How can I find the number of characters that are unaccented English letters?
英文:
I'm trying to count the number of characters that are unaccented English letters in a string. For example, I would want the count to be 1 for the string "né!".
I thought I would be able to check if each character is in the range 'a'-'z' or 'A'-'Z', but that would include 'é'
:
'é' >= 'a' && 'e' <= 'z';
true
Both accented and unaccented letters seem to have the same code point:
"eé".codePointAt(0);
101
"eé".codePointAt(1);
101
I tried using regular expressions, but the string "né!"
was treated like the 4-character string "ne'!"
:
for (let i = 0; i < len; i++) {
var c = str.charAt(i);
if (re.test(c)) {
console.log("Is a letter: " + c);
numLetters++;
} else {
console.log("Is not a letter: " + c);
}
}
Output:
Is a letter: n
Is a letter: e
Is not a letter: ́
Is not a letter: !
How can I find the number of characters that are unaccented English letters?
答案1
得分: 0
您可以使用 String#normalize
来获取字符串的组合形式。
let str = "né!";
let letters = str.normalize().match(/[a-z]/ig);
console.log(letters?.length ?? 0);
console.log(letters);
如果您需要进一步的帮助,请随时提出问题。
英文:
You can use String#normalize
to get the composed form of a string.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let str = "né!";
let letters = str.normalize().match(/[a-z]/ig);
console.log(letters?.length ?? 0);
console.log(letters);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论