NullPoiиteя NullPoiиteя - 1 year ago 79
Javascript Question

How to check string length with JavaScript

I want to get the string length when a key is pressed like StackOverflow does.

Example of StackOverflow showing length

I have tried to do this with

, but it's not working. How do I do this?

Answer Source

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, '