Character limit of a javascript string variable

前端 未结 3 672
无人及你
无人及你 2021-02-19 00:36

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

相关标签:
3条回答
  • 2021-02-19 01:14

    There is no theorical limit to JS or PHP on the size of their strings.

    I think there are a few possible situations.

    Firstly, check that you are not sending your string via HTTP GET. There is a maximum size for GET and i think its dependent on your web server.

    Secondly, if you do use POST, check in php.ini for post_max_size and see if it is smaller than the string size you are sending to it as well as your .htacccess file to see if php_value post_max_size is not too small.

    Thirdly, check that in php.ini that your memory_limit does not restrict the size of memory that your script can use.

    hope this helps.

    0 讨论(0)
  • 2021-02-19 01:20

    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:

    • 1,073,741,822 limit in Firefox 84
    • 536,870,888 limit in Chrome 87

    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);

    0 讨论(0)
  • 2021-02-19 01:36

    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.

    0 讨论(0)
提交回复
热议问题