String Length in JavaScript

str.length. Emoji can be 2 code units. length is UTF-16, not characters.

BeginnerString ProgramsExample 1 of 5
string-length.js
1// Method 1: Using length property
2let str = "Hello World";
3console.log("String:", str);
4console.log("Length:", str.length);
5
6// Method 2: Manual count using loop
7function stringLength(str) {
8 let count = 0;
9 for (let i = 0; i < str.length; i++) {
10 count++;
11 }
12 return count;
13}
14
15console.log("\nManual count:", stringLength("JavaScript"));
16
17// Method 3: Using split and length
18function stringLengthSplit(str) {
19 return str.split('').length;
20}
21
22console.log("Using split:", stringLengthSplit("Programming"));
23
24// Method 4: Count without spaces
25function stringLengthNoSpaces(str) {
26 return str.replace(/\s/g, '').length;
27}
28
29console.log("\nLength without spaces:", stringLengthNoSpaces("Hello World"));
30
31// Method 5: Count words
32function countWords(str) {
33 return str.trim().split(/\s+/).length;
34}
35
36console.log("Word count:", countWords("Hello World from JavaScript"));

Output

String: Hello World
Length: 11

Manual count: 10

Using split: 11

Length without spaces: 10

Word count: 4

What's going on

'hi'.length is 2. '👍'.length is 2 as well. Surrogate pairs.

[...str].length counts code points better. For this page, .length is fine.