Character limit of a javascript string variable

前端 未结 3 691
无人及你
无人及你 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: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);

提交回复
热议问题