Can JavaScript string store 100K characters? I've written a script where a string from PHP is passed to a variable in JavaScript. It works fine when it is cut short to almost ten thousand characters but breaks the script when attempting to pass the entire string whose length is a bit greater than 100K. No errors could be found though. Is there any solution for this as to any way of increasing character limit of JavaScript variable? I'm just a beginner. Would appreciate is some one could find a solution for this.
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values ("elements") up to a maximum length of 253-1 elements. So don't plan on using more than 9,007,199,254,740,991 or about 9 quadrillion characters.
ECMAScript 2016 (ed. 7) established a maximum length of 253 - 1 elements. Previously, no maximum length was specified. In Firefox, strings have a maximum length of 230 - 2 (~1GB).
Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.
JavaScript does not return the length but rather returns the code units occupied by the string. It uses the UTF-16 string formatting methods to store characters. This essentially means that the characters in your string are encoded into a 16-bit long binary number before being stored.
The ECMAScript Standard ECMA-262 (6th Edition, June 2015) says
6.1.4 The String Type
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values ("elements") up to a maximum length of 253-1 elements.
So don't plan on using more than 9,007,199,254,740,991 or about 9 quadrillion characters. Of course, you should be prepared for systems which cannot allocate 18 PB chunks of memory, as this is not required for conforming ECMAScript implementations.
I think the question is asking about the practical limit, not the spec limit. And, no, it is not always the amount of RAM you have. I have x86_64 24GB PC running Linux Mint with x86_64 Firefox and x86_64 Chrome, and the limits I ran into were:
Any higher and Firefox throws a Uncaught RangeError: repeat count must be less than infinity and not overflow maximum string size
, whereas Chrome throws Uncaught RangeError: Invalid string length
. Use the following snippet to run a binary search for the max string length in your browser:
for (var startPow2 = 1; startPow2 < 9007199254740992; startPow2 *= 2) try {" ".repeat(startPow2);} catch(e) { break; } var floor = Math.floor, mask = floor(startPow2 / 2); while (startPow2 = floor(startPow2 / 2)) try { " ".repeat(mask + startPow2); mask += startPow2; // the previous statement succeeded } catch(e) {} console.log("The max string length for this browser is " + mask);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With