What is function length in JavaScript

As for the question which event you should use for this: use the event, and fall back to / in older browsers.

Here’s an example, DOM0-style:


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 answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, , as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, , 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:

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.