10 examples of 'how to find length of string in javascript' in JavaScript

Every line of 'how to find length of string in javascript' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
11function stringLength(str){
12 return str
13 .replace(ansiRegex, '')
14 .replace(reAstral, ' ')
15 .length;
16}
6function strLength(str: string) {
7 return str.replace(spRegexp, '_').length;
8}
585function calculateLength (str) {
586 var ch = []
587 var st = []
588 var re = []
589 for (var i = 0; i < str.length; i++) {
590 ch = str.charCodeAt(i)
591 st = []
592 do {
593 st.push(ch & 0xFF)
594 ch = ch >> 8
595 } while (ch)
596 re = re.concat(st.reverse())
597 }
598 // return an array of bytes.
599 return re.length
600}
1function strlen(str) {
2 return str.replace(/\u001b[^m]*m/g, '').length
3}
483export function utf8Length(str: string): number {
484 let bytes = 0;
485 let length = str.length;
486 for(let ix = 0; ix < length; ix++) {
487 let c = str.charCodeAt(ix);
488 if(c < 0x80)
489 bytes++;
490 else if(c < 0x800)
491 bytes += 2;
492 else
493 bytes += 3;
494 }
495 return bytes;
496}
61function byteLength(str) {
62 if (!str) {
63 return 0;
64 }
65 var matched = str.match(/[^\x00-\xff]/g);
66 return (str.length + (!matched ? 0 : matched.length));
67}
408function utf8Length(str) {
409 var bytes = 0;
410 var length = str.length;
411 for (var ix = 0; ix < length; ix++) {
412 var c = str.charCodeAt(ix);
413 if (c < 0x80)
414 bytes++;
415 else if (c < 0x800)
416 bytes += 2;
417 else
418 bytes += 3;
419 }
420 return bytes;
421}
30function lengthInUtf8Bytes (str) {
31 // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
32 const m = encodeURIComponent(str).match(/%[89ABab]/g)
33 return str.length + (m ? m.length : 0)
34}
105function strlen(str) {
106 // Call the native functions if there's no surrogate char
107 if (!hasSurrogateUnit(str)) {
108 return str.length;
109 }
110
111 let len = 0;
112 for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
113 len++;
114 }
115 return len;
116}
3export function get_text_length(text) {
4 const trimmed_text = text.trim();
5 const condensed_text = trimmed_text.replace(/\s\s+/g, ' ');
6 return condensed_text.length;
7}

Related snippets