如何在JavaScript中计算无重音的英文字母?

huangapple go评论60阅读模式
英文:

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 &#39;é&#39;:

&#39;é&#39; &gt;= &#39;a&#39; &amp;&amp; &#39;e&#39; &lt;= &#39;z&#39;;
true

Both accented and unaccented letters seem to have the same code point:

&quot;eé&quot;.codePointAt(0);
101
&quot;eé&quot;.codePointAt(1);
101

I tried using regular expressions, but the string &quot;né!&quot; was treated like the 4-character string &quot;ne&#39;!&quot;:

	for (let i = 0; i &lt; len; i++) {
	    var c = str.charAt(i);
	    if (re.test(c)) {
		    console.log(&quot;Is a letter: &quot; + c);
		    numLetters++;
	    } else {
		   console.log(&quot;Is not a letter: &quot; + 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 = &quot;né!&quot;;
let letters = str.normalize().match(/[a-z]/ig);
console.log(letters?.length ?? 0);
console.log(letters);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月24日 08:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定