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.

Answer from Mathias Bynens on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › length
String: length - JavaScript | MDN
It's the arity of the String function (loosely, the number of formal parameters it has), which is 1. Since length counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:
Discussions

Basic JavaScript - Find the Length of a String
You can find the length of a String value by writing .length after the string variable or string literal. console.log("Alan Peter".length); The value 10 would be displayed in the console. Note that the space character between “Alan” and “Peter” is also counted. More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
November 9, 2023
How does String.length work in JavaScript? - Stack Overflow
I want to know how is the string length of a string calculated in js. Is is a function call or a class data member. I want to know what happens when we execute the following code : a = 'this is a ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Create a string of variable length, filled with a repeated character - Stack Overflow
So, my question has been asked by someone else in it's Java form here: Java - Create a new String instance with specified length and filled with specific character. Best solution? . . . but I'm lo... More on stackoverflow.com
🌐 stackoverflow.com
Javascript, string length function.
if (x.legnth === y.legnth){ You misspelled length. Also, x.length === y.length will either return true or false. So you don't need to do this... if (x.length === y.length) { return true; } else { return false; } ...when you could just do this: return x.length === y.length; More on reddit.com
🌐 r/learnprogramming
11
1
September 20, 2017
Top answer
1 of 11
47

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.

2 of 11
15

UPDATE: Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

Use keyup event

var inp = document.getElementById('myinput');
var chars = document.getElementById('chars');
inp.onkeyup = function() {
  chars.innerHTML = inp.value.length;
}
<input id="myinput"><span id="chars">0</span>

EDIT:

Just a note for those that suggest keydown. That won't work. The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires after the character is added.

🌐
Tabnine
tabnine.com › home › how to use the string length property in javascript
How to Use the String length Property in JavaScript - Tabnine
July 25, 2024 - The length property of a String object returns the number of characters contained in a string. const str = 'Get the length of this string'; console.log(str.length); // Expected output: 29 In the example above, str is a String containing 29 ...
🌐
ReqBin
reqbin.com › code › javascript › 6onvgezc › javascript-string-length-example
How do I get the length of a string in JavaScript?
December 16, 2022 - To get the length of a string in JavaScript, you can to use the string.length property. The length property specifies how many characters the string contains (the length of an empty string is 0). When determining the length of a string, keep ...
🌐
Etleap
etleap.com › blog › what-is-the-length-of-a-string
What is the “length” of a string? - Etleap
For example, "😃" has a length ... the properties panel. Finding the length of a string in JavaScript is simple, you use the .length property and that’s it, right?...
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Find the Length of a String - JavaScript - The freeCodeCamp Forum
November 9, 2023 - You can find the length of a String value by writing .length after the string variable or string literal. console.log("Alan Peter".length); The value 10 would be displayed in the console.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › String › length
JavaScript String length - Get Length of String | Vultr Docs
April 10, 2025 - This code declares a string ... string, which outputs 13. The JavaScript string length function counts all characters, including spaces and punctuation....
🌐
Medium
medium.com › @amirakhaled2027 › string-length-vs-string-size-in-javascript-393ec8d77a3b
string.length vs string.size in JavaScript | by Amira Khaled | Medium
August 24, 2024 - The string.length property returns the number of characters in a string, including spaces, punctuation marks, and special characters.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-string-length
JavaScript string.length - GeeksforGeeks
July 11, 2025 - The string.length is a property in JS which is used to find the length of a given string.
🌐
Codecademy
codecademy.com › docs › javascript › storage › .length
JavaScript | Storage | .length | Codecademy
July 8, 2025 - In JavaScript, the .length property is used to determine the number of elements, characters, or items in a given data structure, such as arrays or strings.
🌐
Flexiple
flexiple.com › javascript › javascript-string-length
JavaScript String Length property explained | Flexiple Tutorials | JavaScript - Flexiple
March 11, 2022 - This essentially means that the characters in your string are encoded into a 16-bit long binary number before being stored. So whenever the .length property is involved, JavaScript looks up and returns the number of code units occupied by the string.
Top answer
1 of 3
7

A string is immutable in JavaScript.

a += "somestring" doesn't change the length of a string but makes a new string.

This means there is no "new length", but the length is just part of the definition of the string (more precisely it is stored in the same structure in implementations).

Regarding

for(i=0;i<a.length;i++){ // did you forget the 'var' keyword ?

a not so uncommon practice (if you don't change a) was to optimize it as

for (var i=0, l=a.length; i<l; i++)

in order to avoid the reading of the length but if you compare the performances with modern engines, you'll see this doesn't make the code any faster now.

What you must remember : querying the length of a string is fast because there is no computation. What's a little less fast is building strings (for example with concatenation).

2 of 3
5

Strings are a primitive type. At least that's what the documentation says. But we can access the length of the string as if we are accessing the property of an object(with the dot notation). Which indicates it's an object, Right?

Turns out, whenever we make a call from the string primitive to some property using the dot notation (for example, say length), the Js engine will take this primitive string and wrap it into an equivalent wrapper object, which is a String object. And then, the .length on that String object returns the length.

Interesting thing to note here is, that when we do something like this, our string still stays the same primitive string during all of this. And a temporary object is created to make our string operation work. Once the required property is fetched, this temporary object is deleted from the memory.

Hope this gives some high level understanding.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-find-the-length-of-a-string
JavaScript - Length of a String - GeeksforGeeks
July 23, 2025 - This approach directly utilizes the built-in length property of strings in JavaScript, which returns the number of characters in the given string.
🌐
Programiz
programiz.com › javascript › library › string › length
JavaScript String length (with Examples)
We have then used the length property to find out the number of characters in string1. Since 'JavaScript' contains 10 characters, string1.length returns 10.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String
String - JavaScript | MDN
Pads the current string from the end with a given string and returns a new string of the length targetLength.
🌐
W3Schools
w3schools.com › howto › howto_js_string_length.asp
How To Get The Length of a String in JavaScript
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var len = txt.length; Try it Yourself » · Read more about strings in our JavaScript Strings Tutorial.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
October 20, 2025 - Constructs a new String by decoding the specified subarray of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.