As for the question which event you should use for this: use the input
event, and fall back to keyup
/keydown
in older browsers.
Here’s an example, DOM0-style:
someElement.oninput = function() {
this.onkeydown = null;
// Your code goes here
};
someElement.onkeydown = function() {
// Your code goes here
};
The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length
answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1
, as you’d expect.
However, for supplementary (non-BMP) symbols, things are a bit different. For example, '??'.length == 2
, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.
Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:
// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('??').length; // 1 (note that `'??'.length == 2`!)
P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering ??
, and you’ll see that it (incorrectly) counts as two characters.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…