JS: Count Chars in String 📜
Quick solution
console.log(Array.from("🌞🦋").length); // 2
Memory efficient solution
/* xah_string_char_count(zstr) return number of chars in string zstr. URL http://xahlee.info/js/js_string_real_length.html Created: 2018-06-17 Version: 2026-01-13 */ const xah_string_char_count = (zstr) => { let xtotal = 0; for (let _ of zstr) xtotal++; return xtotal; }; // s------------------------------ // test console.log(xah_string_char_count("🦋")); // 1
test speed and memory
// file name: bench.js const fa = (zstr) => ([...zstr].length); const fb = (zstr) => { let xtotal = 0; for (let _ of zstr) xtotal++; return xtotal; }; /* fgenStr(xcharArray, xcount) returns a array of length xcount. elements are randomly selected from array xcharArray. */ const fgenStr = (xcharArray, xcount) => { const xlen = xcharArray.length; return (Array.from(Array(xcount), () => xcharArray[Math.floor(Math.random() * xlen)])); }; const xbigstring = fgenStr(["a", "b", "⭐", "🦋"], 10 ** 4).join(""); console.log("string length is ", xbigstring.length); console.log("fa result is", fa(xbigstring)); console.log("fb result is", fb(xbigstring)); // s------------------------------ Deno.bench("test fa", () => { fa(xbigstring); }); Deno.bench("test fb", () => { fb(xbigstring); });
JavaScript. String
- JS: String Overview
- JS: Quote String
- JS: Apostrophe Delimiter String
- JS: Template String
- JS: String Escape Sequence
- JS: Unicode Escape Sequence
- JS: String Operations
- JS: Iterate String
- JS: String Code Unit
- JS: Count Chars in String 📜
- JS: Tagged Template String
- JS: Regular Expression Functions
- JS: Convert String and Number
- JS: String (class)
- JS: String Constructor
- JS: String.prototype