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 property2let str = "Hello World";3console.log("String:", str);4console.log("Length:", str.length);56// Method 2: Manual count using loop7function stringLength(str) {8 let count = 0;9 for (let i = 0; i < str.length; i++) {10 count++;11 }12 return count;13}1415console.log("\nManual count:", stringLength("JavaScript"));1617// Method 3: Using split and length18function stringLengthSplit(str) {19 return str.split('').length;20}2122console.log("Using split:", stringLengthSplit("Programming"));2324// Method 4: Count without spaces25function stringLengthNoSpaces(str) {26 return str.replace(/\s/g, '').length;27}2829console.log("\nLength without spaces:", stringLengthNoSpaces("Hello World"));3031// Method 5: Count words32function countWords(str) {33 return str.trim().split(/\s+/).length;34}3536console.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.