在JavaScript中将大字符串分割成n大小的块

时间:2021-12-16 17:34:44

I would like to split a very large string (let's say, 10,000 characters) into N-size chunks.

我想将一个非常大的字符串(比方说10,000个字符)分割成n大小的块。

What would be the best way in terms of performance to do this?

在性能方面,最好的方法是什么?

For instance:"1234567890" split by 2 would become ["12", "34", "56", "78", "90"].

例如:“1234567890”除以2就变成了“12”、“34”、“56”、“78”、“90”。

Would something like this be possible using String.prototype.match and if so, would that be the best way to do it in terms of performance?

使用String.prototype这样的东西可能吗?如果是这样的话,这是最好的表现方式吗?

15 个解决方案

#1


286  

You can do something like this:

你可以这样做:

"1234567890".match(/.{1,2}/g);// Results in:["12", "34", "56", "78", "90"]

The method will still work with strings whose size is not an exact multiple of the chunk-size:

该方法仍然适用于尺寸不是块大小的精确倍数的字符串:

"123456789".match(/.{1,2}/g);// Results in:["12", "34", "56", "78", "9"]

In general, for any string out of which you want to extract at-most n-sized substrings, you would do:

一般来说,对于任何您想要从中提取出的最大n级子字符串,您可以这样做:

str.match(/.{1,n}/g); // Replace n with the size of the substring

If your string can contain newlines or carriage returns, you would do:

如果您的字符串可以包含换行符或回车符,您可以这样做:

str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.

至于性能,我试用了大约10k个字符,在Chrome上花了一秒钟多一点的时间。YMMV。

This can also be used in a reusable function:

这也可用于可重复使用的功能:

function chunkString(str, length) {  return str.match(new RegExp('.{1,' + length + '}', 'g'));}

#2


25  

Bottom line:

底线:

  • match is very inefficient, slice is better, on Firefox substr/substring is better still
  • 匹配非常低效,slice更好,在Firefox substr/substring上更好
  • match is even more inefficient for short strings (even with cached regex - probably due to regex parsing setup time)
  • 对于短字符串(甚至对于缓存的regex——可能由于regex解析设置时间),match的效率甚至更低。
  • match is even more inefficient for large chunk size (probably due to inability to "jump")
  • 对于大型块大小(可能是由于无法“跳转”),匹配更低效。
  • for longer strings with very small chunk size, match outperforms slice on older IE but still loses on all other systems
  • 对于非常小块大小的较长字符串,match在较老的IE上优于slice,但在所有其他系统上仍然会丢失。
  • jsperf rocks
  • jsperf岩石

#3


16  

I created several faster variants which you can see on jsPerf. My favorite one is this:

我创建了几个更快的变种你们可以在jsPerf上看到。我最喜欢的一个是:

function chunkSubstr(str, size) {  const numChunks = Math.ceil(str.length / size)  const chunks = new Array(numChunks)  for (let i = 0, o = 0; i < numChunks; ++i, o += size) {    chunks[i] = str.substr(o, size)  }  return chunks}

#4


13  

This is the fastest, most performant solution:

这是最快、最有效的解决方案:

function chunkString(str, len) {  var _size = Math.ceil(str.length/len),      _ret  = new Array(_size),      _offset  ;  for (var _i=0; _i<_size; _i++) {    _offset = _i * len;    _ret[_i] = str.substring(_offset, _offset + len);  }  return _ret;}

Compare it to the others; I win :)

把它和其他的比较;我赢了:)

#5


3  

var str = "123456789";var chunks = [];var chunkSize = 2;while (str) {    if (str.length < chunkSize) {        chunks.push(str);        break;    }    else {        chunks.push(str.substr(0, chunkSize));        str = str.substr(chunkSize);    }}alert(chunks); // chunks == 12,34,56,78,9

#6


3  

I have written an extended function, so the chunk length can also be an array of numbers, like [1,3]

我已经写了一个扩展函数,所以块长度也可以是一个数字数组,比如[1,3]

String.prototype.chunkString = function(len) {    var _ret;    if (this.length < 1) {        return [];    }    if (typeof len === 'number' && len > 0) {        var _size = Math.ceil(this.length / len), _offset = 0;        _ret = new Array(_size);        for (var _i = 0; _i < _size; _i++) {            _ret[_i] = this.substring(_offset, _offset = _offset + len);        }    }    else if (typeof len === 'object' && len.length) {        var n = 0, l = this.length, chunk, that = this;        _ret = [];        do {            len.forEach(function(o) {                chunk = that.substring(n, n + o);                if (chunk !== '') {                    _ret.push(chunk);                    n += chunk.length;                }            });            if (n === 0) {                return undefined; // prevent an endless loop when len = [0]            }        } while (n < l);    }    return _ret;};

The code

的代码

"1234567890123".chunkString([1,3])

will return:

将返回:

[ '1', '234', '5', '678', '9', '012', '3' ]

#7


2  

it Split's large string in to Small strings of given words .

它把大字符串分割成小字符串。

function chunkSubstr(str, words) {  var parts = str.split(" ") , values = [] , i = 0 , tmpVar = "";  $.each(parts, function(index, value) {      if(tmpVar.length < words){          tmpVar += " " + value;      }else{          values[i] = tmpVar.replace(/\s+/g, " ");          i++;          tmpVar = value;      }  });  if(values.length < 1 &&  parts.length > 0){      values[0] = tmpVar;  }  return values;}

#8


1  

var l = str.length, lc = 0, chunks = [], c = 0, chunkSize = 2;for (; lc < l; c++) {  chunks[c] = str.slice(lc, lc += chunkSize);}

#9


1  

I would use a regex...

我会使用regex…

var chunkStr = function(str, chunkLength) {    return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));}

#10


0  

In the form of a prototype function:

以原型函数的形式:

String.prototype.lsplit = function(){    return this.match(new RegExp('.{1,'+ ((arguments.length==1)?(isFinite(String(arguments[0]).trim())?arguments[0]:false):1) +'}', 'g'));}

#11


0  

Here is the code that I am using, it uses String.prototype.slice.

这是我正在使用的代码,它使用String.prototype.slice。

Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of JSDOC comments. However, once minified, the code is only 828 bytes and once gzipped for transmission it is only 497 bytes.

是的,答案很长,因为它尽可能地遵循当前的标准,当然包含了相当多的JSDOC注释。然而,一旦缩小,代码只有828字节,而一旦gziked进行传输,代码只有497字节。

The 1 method that this adds to String.prototype (using Object.defineProperty where available) is:

添加到字符串的1个方法。原型(使用Object.defineProperty,如果有的话)是:

  1. toChunks
  2. toChunks

A number of tests have been included to check the functionality.

已经包含了许多测试来检查功能。

Worried that the length of code will affect the performance? No need to worry, http://jsperf.com/chunk-string/3

担心代码长度会影响性能吗?无需担心,http://jsperf.com/chunk-string/3

Much of the extra code is there to be sure that the code will respond the same across multiple javascript environments.

很多额外的代码都是为了确保代码在多个javascript环境中响应相同。

/*jslint maxlen:80, browser:true, devel:true *//* * Properties used by toChunks. *//*property    MAX_SAFE_INTEGER, abs, ceil, configurable, defineProperty, enumerable,    floor, length, max, min, pow, prototype, slice, toChunks, value,    writable*//* * Properties used in the testing of toChunks implimentation. *//*property    appendChild, createTextNode, floor, fromCharCode, getElementById, length,    log, pow, push, random, toChunks*/(function () {    'use strict';    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;    /**     * Defines a new property directly on an object, or modifies an existing     * property on an object, and returns the object.     *     * @private     * @function     * @param {Object} object     * @param {string} property     * @param {Object} descriptor     * @return {Object}     * @see https://goo.gl/CZnEqg     */    function $defineProperty(object, property, descriptor) {        if (Object.defineProperty) {            Object.defineProperty(object, property, descriptor);        } else {            object[property] = descriptor.value;        }        return object;    }    /**     * Returns true if the operands are strictly equal with no type conversion.     *     * @private     * @function     * @param {*} a     * @param {*} b     * @return {boolean}     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4     */    function $strictEqual(a, b) {        return a === b;    }    /**     * Returns true if the operand inputArg is undefined.     *     * @private     * @function     * @param {*} inputArg     * @return {boolean}     */    function $isUndefined(inputArg) {        return $strictEqual(typeof inputArg, 'undefined');    }    /**     * The abstract operation throws an error if its argument is a value that     * cannot be converted to an Object, otherwise returns the argument.     *     * @private     * @function     * @param {*} inputArg The object to be tested.     * @throws {TypeError} If inputArg is null or undefined.     * @return {*} The inputArg if coercible.     * @see https://goo.gl/5GcmVq     */    function $requireObjectCoercible(inputArg) {        var errStr;        if (inputArg === null || $isUndefined(inputArg)) {            errStr = 'Cannot convert argument to object: ' + inputArg;            throw new TypeError(errStr);        }        return inputArg;    }    /**     * The abstract operation converts its argument to a value of type string     *     * @private     * @function     * @param {*} inputArg     * @return {string}     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring     */    function $toString(inputArg) {        var type,            val;        if (inputArg === null) {            val = 'null';        } else {            type = typeof inputArg;            if (type === 'string') {                val = inputArg;            } else if (type === 'undefined') {                val = type;            } else {                if (type === 'symbol') {                    throw new TypeError('Cannot convert symbol to string');                }                val = String(inputArg);            }        }        return val;    }    /**     * Returns a string only if the arguments is coercible otherwise throws an     * error.     *     * @private     * @function     * @param {*} inputArg     * @throws {TypeError} If inputArg is null or undefined.     * @return {string}     */    function $onlyCoercibleToString(inputArg) {        return $toString($requireObjectCoercible(inputArg));    }    /**     * The function evaluates the passed value and converts it to an integer.     *     * @private     * @function     * @param {*} inputArg The object to be converted to an integer.     * @return {number} If the target value is NaN, null or undefined, 0 is     *                   returned. If the target value is false, 0 is returned     *                   and if true, 1 is returned.     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4     */    function $toInteger(inputArg) {        var number = +inputArg,            val = 0;        if ($strictEqual(number, number)) {            if (!number || number === Infinity || number === -Infinity) {                val = number;            } else {                val = (number > 0 || -1) * Math.floor(Math.abs(number));            }        }        return val;    }    /**     * The abstract operation ToLength converts its argument to an integer     * suitable for use as the length of an array-like object.     *     * @private     * @function     * @param {*} inputArg The object to be converted to a length.     * @return {number} If len <= +0 then +0 else if len is +INFINITY then     *                   2^53-1 else min(len, 2^53-1).     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength     */    function $toLength(inputArg) {        return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);    }    if (!String.prototype.toChunks) {        /**         * This method chunks a string into an array of strings of a specified         * chunk size.         *         * @function         * @this {string} The string to be chunked.         * @param {Number} chunkSize The size of the chunks that the string will         *                           be chunked into.         * @returns {Array} Returns an array of the chunked string.         */        $defineProperty(String.prototype, 'toChunks', {            enumerable: false,            configurable: true,            writable: true,            value: function (chunkSize) {                var str = $onlyCoercibleToString(this),                    chunkLength = $toInteger(chunkSize),                    chunked = [],                    numChunks,                    length,                    index,                    start,                    end;                if (chunkLength < 1) {                    return chunked;                }                length = $toLength(str.length);                numChunks = Math.ceil(length / chunkLength);                index = 0;                start = 0;                end = chunkLength;                chunked.length = numChunks;                while (index < numChunks) {                    chunked[index] = str.slice(start, end);                    start = end;                    end += chunkLength;                    index += 1;                }                return chunked;            }        });    }}());/* * Some tests */(function () {    'use strict';    var pre = document.getElementById('out'),        chunkSizes = [],        maxChunkSize = 512,        testString = '',        maxTestString = 100000,        chunkSize = 0,        index = 1;    while (chunkSize < maxChunkSize) {        chunkSize = Math.pow(2, index);        chunkSizes.push(chunkSize);        index += 1;    }    index = 0;    while (index < maxTestString) {        testString += String.fromCharCode(Math.floor(Math.random() * 95) + 32);        index += 1;    }    function log(result) {        pre.appendChild(document.createTextNode(result + '\n'));    }    function test() {        var strLength = testString.length,            czLength = chunkSizes.length,            czIndex = 0,            czValue,            result,            numChunks,            pass;        while (czIndex < czLength) {            czValue = chunkSizes[czIndex];            numChunks = Math.ceil(strLength / czValue);            result = testString.toChunks(czValue);            czIndex += 1;            log('chunksize: ' + czValue);            log(' Number of chunks:');            log('  Calculated: ' + numChunks);            log('  Actual:' + result.length);            pass = result.length === numChunks;            log(' First chunk size: ' + result[0].length);            pass = pass && result[0].length === czValue;            log(' Passed: ' + pass);            log('');        }    }    test();    log('');    log('Simple test result');    log('abcdefghijklmnopqrstuvwxyz'.toChunks(3));}());
<pre id="out"></pre>

#12


0  

    window.format = function(b, a) {        if (!b || isNaN(+a)) return a;        var a = b.charAt(0) == "-" ? -a : +a,            j = a < 0 ? a = -a : 0,            e = b.match(/[^\d\-\+#]/g),            h = e && e[e.length - 1] || ".",            e = e && e[1] && e[0] || ",",            b = b.split(h),            a = a.toFixed(b[1] && b[1].length),            a = +a + "",            d = b[1] && b[1].lastIndexOf("0"),            c = a.split(".");        if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1);        d = b[0].split(e);        b[0] = d.join("");        var f = b[0] && b[0].indexOf("0");        if (f > -1)            for (; c[0].length < b[0].length - f;) c[0] = "0" + c[0];        else +c[0] == 0 && (c[0] = "");        a = a.split(".");        a[0] = c[0];        if (c = d[1] && d[d.length -                1].length) {            for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e);            a[0] = f        }        a[1] = b[1] && a[1] ? h + a[1] : "";        return (j ? "-" : "") + a[0] + a[1]    };var str="1234567890";var formatstr=format( "##,###.", str);alert(formatstr);This will split the string in reverse order with comma separated after 3 char's. If you want you can change the position.

#13


0  

Using slice() method:

使用切片()方法:

function returnChunksArray(str, chunkSize) {  var arr = [];  while(str !== '') {    arr.push(str.slice(0, chunkSize));    str = str.slice(chunkSize);  }  return arr;}

The same can be done using substring() method.

使用substring()方法也可以这样做。

function returnChunksArray(str, chunkSize) {  var arr = [];  while(str !== '') {    arr.push(str.substring(0, chunkSize));    str = str.substring(chunkSize);  }  return arr;}

#14


0  

What about this small piece of code:

这一小段代码:

function splitME(str, size) {    let subStr = new RegExp('.{1,' + size + '}', 'g');    return str.match(subStr);};

#15


-1  

function chunkString(str, length = 10) {    let result = [],        offset = 0;    if (str.length <= length) return result.push(str) && result;    while (offset < str.length) {        result.push(str.substr(offset, length));        offset += length;    }    return result;}

#1


286  

You can do something like this:

你可以这样做:

"1234567890".match(/.{1,2}/g);// Results in:["12", "34", "56", "78", "90"]

The method will still work with strings whose size is not an exact multiple of the chunk-size:

该方法仍然适用于尺寸不是块大小的精确倍数的字符串:

"123456789".match(/.{1,2}/g);// Results in:["12", "34", "56", "78", "9"]

In general, for any string out of which you want to extract at-most n-sized substrings, you would do:

一般来说,对于任何您想要从中提取出的最大n级子字符串,您可以这样做:

str.match(/.{1,n}/g); // Replace n with the size of the substring

If your string can contain newlines or carriage returns, you would do:

如果您的字符串可以包含换行符或回车符,您可以这样做:

str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.

至于性能,我试用了大约10k个字符,在Chrome上花了一秒钟多一点的时间。YMMV。

This can also be used in a reusable function:

这也可用于可重复使用的功能:

function chunkString(str, length) {  return str.match(new RegExp('.{1,' + length + '}', 'g'));}

#2


25  

Bottom line:

底线:

  • match is very inefficient, slice is better, on Firefox substr/substring is better still
  • 匹配非常低效,slice更好,在Firefox substr/substring上更好
  • match is even more inefficient for short strings (even with cached regex - probably due to regex parsing setup time)
  • 对于短字符串(甚至对于缓存的regex——可能由于regex解析设置时间),match的效率甚至更低。
  • match is even more inefficient for large chunk size (probably due to inability to "jump")
  • 对于大型块大小(可能是由于无法“跳转”),匹配更低效。
  • for longer strings with very small chunk size, match outperforms slice on older IE but still loses on all other systems
  • 对于非常小块大小的较长字符串,match在较老的IE上优于slice,但在所有其他系统上仍然会丢失。
  • jsperf rocks
  • jsperf岩石

#3


16  

I created several faster variants which you can see on jsPerf. My favorite one is this:

我创建了几个更快的变种你们可以在jsPerf上看到。我最喜欢的一个是:

function chunkSubstr(str, size) {  const numChunks = Math.ceil(str.length / size)  const chunks = new Array(numChunks)  for (let i = 0, o = 0; i < numChunks; ++i, o += size) {    chunks[i] = str.substr(o, size)  }  return chunks}

#4


13  

This is the fastest, most performant solution:

这是最快、最有效的解决方案:

function chunkString(str, len) {  var _size = Math.ceil(str.length/len),      _ret  = new Array(_size),      _offset  ;  for (var _i=0; _i<_size; _i++) {    _offset = _i * len;    _ret[_i] = str.substring(_offset, _offset + len);  }  return _ret;}

Compare it to the others; I win :)

把它和其他的比较;我赢了:)

#5


3  

var str = "123456789";var chunks = [];var chunkSize = 2;while (str) {    if (str.length < chunkSize) {        chunks.push(str);        break;    }    else {        chunks.push(str.substr(0, chunkSize));        str = str.substr(chunkSize);    }}alert(chunks); // chunks == 12,34,56,78,9

#6


3  

I have written an extended function, so the chunk length can also be an array of numbers, like [1,3]

我已经写了一个扩展函数,所以块长度也可以是一个数字数组,比如[1,3]

String.prototype.chunkString = function(len) {    var _ret;    if (this.length < 1) {        return [];    }    if (typeof len === 'number' && len > 0) {        var _size = Math.ceil(this.length / len), _offset = 0;        _ret = new Array(_size);        for (var _i = 0; _i < _size; _i++) {            _ret[_i] = this.substring(_offset, _offset = _offset + len);        }    }    else if (typeof len === 'object' && len.length) {        var n = 0, l = this.length, chunk, that = this;        _ret = [];        do {            len.forEach(function(o) {                chunk = that.substring(n, n + o);                if (chunk !== '') {                    _ret.push(chunk);                    n += chunk.length;                }            });            if (n === 0) {                return undefined; // prevent an endless loop when len = [0]            }        } while (n < l);    }    return _ret;};

The code

的代码

"1234567890123".chunkString([1,3])

will return:

将返回:

[ '1', '234', '5', '678', '9', '012', '3' ]

#7


2  

it Split's large string in to Small strings of given words .

它把大字符串分割成小字符串。

function chunkSubstr(str, words) {  var parts = str.split(" ") , values = [] , i = 0 , tmpVar = "";  $.each(parts, function(index, value) {      if(tmpVar.length < words){          tmpVar += " " + value;      }else{          values[i] = tmpVar.replace(/\s+/g, " ");          i++;          tmpVar = value;      }  });  if(values.length < 1 &&  parts.length > 0){      values[0] = tmpVar;  }  return values;}

#8


1  

var l = str.length, lc = 0, chunks = [], c = 0, chunkSize = 2;for (; lc < l; c++) {  chunks[c] = str.slice(lc, lc += chunkSize);}

#9


1  

I would use a regex...

我会使用regex…

var chunkStr = function(str, chunkLength) {    return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));}

#10


0  

In the form of a prototype function:

以原型函数的形式:

String.prototype.lsplit = function(){    return this.match(new RegExp('.{1,'+ ((arguments.length==1)?(isFinite(String(arguments[0]).trim())?arguments[0]:false):1) +'}', 'g'));}

#11


0  

Here is the code that I am using, it uses String.prototype.slice.

这是我正在使用的代码,它使用String.prototype.slice。

Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of JSDOC comments. However, once minified, the code is only 828 bytes and once gzipped for transmission it is only 497 bytes.

是的,答案很长,因为它尽可能地遵循当前的标准,当然包含了相当多的JSDOC注释。然而,一旦缩小,代码只有828字节,而一旦gziked进行传输,代码只有497字节。

The 1 method that this adds to String.prototype (using Object.defineProperty where available) is:

添加到字符串的1个方法。原型(使用Object.defineProperty,如果有的话)是:

  1. toChunks
  2. toChunks

A number of tests have been included to check the functionality.

已经包含了许多测试来检查功能。

Worried that the length of code will affect the performance? No need to worry, http://jsperf.com/chunk-string/3

担心代码长度会影响性能吗?无需担心,http://jsperf.com/chunk-string/3

Much of the extra code is there to be sure that the code will respond the same across multiple javascript environments.

很多额外的代码都是为了确保代码在多个javascript环境中响应相同。

/*jslint maxlen:80, browser:true, devel:true *//* * Properties used by toChunks. *//*property    MAX_SAFE_INTEGER, abs, ceil, configurable, defineProperty, enumerable,    floor, length, max, min, pow, prototype, slice, toChunks, value,    writable*//* * Properties used in the testing of toChunks implimentation. *//*property    appendChild, createTextNode, floor, fromCharCode, getElementById, length,    log, pow, push, random, toChunks*/(function () {    'use strict';    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;    /**     * Defines a new property directly on an object, or modifies an existing     * property on an object, and returns the object.     *     * @private     * @function     * @param {Object} object     * @param {string} property     * @param {Object} descriptor     * @return {Object}     * @see https://goo.gl/CZnEqg     */    function $defineProperty(object, property, descriptor) {        if (Object.defineProperty) {            Object.defineProperty(object, property, descriptor);        } else {            object[property] = descriptor.value;        }        return object;    }    /**     * Returns true if the operands are strictly equal with no type conversion.     *     * @private     * @function     * @param {*} a     * @param {*} b     * @return {boolean}     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4     */    function $strictEqual(a, b) {        return a === b;    }    /**     * Returns true if the operand inputArg is undefined.     *     * @private     * @function     * @param {*} inputArg     * @return {boolean}     */    function $isUndefined(inputArg) {        return $strictEqual(typeof inputArg, 'undefined');    }    /**     * The abstract operation throws an error if its argument is a value that     * cannot be converted to an Object, otherwise returns the argument.     *     * @private     * @function     * @param {*} inputArg The object to be tested.     * @throws {TypeError} If inputArg is null or undefined.     * @return {*} The inputArg if coercible.     * @see https://goo.gl/5GcmVq     */    function $requireObjectCoercible(inputArg) {        var errStr;        if (inputArg === null || $isUndefined(inputArg)) {            errStr = 'Cannot convert argument to object: ' + inputArg;            throw new TypeError(errStr);        }        return inputArg;    }    /**     * The abstract operation converts its argument to a value of type string     *     * @private     * @function     * @param {*} inputArg     * @return {string}     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring     */    function $toString(inputArg) {        var type,            val;        if (inputArg === null) {            val = 'null';        } else {            type = typeof inputArg;            if (type === 'string') {                val = inputArg;            } else if (type === 'undefined') {                val = type;            } else {                if (type === 'symbol') {                    throw new TypeError('Cannot convert symbol to string');                }                val = String(inputArg);            }        }        return val;    }    /**     * Returns a string only if the arguments is coercible otherwise throws an     * error.     *     * @private     * @function     * @param {*} inputArg     * @throws {TypeError} If inputArg is null or undefined.     * @return {string}     */    function $onlyCoercibleToString(inputArg) {        return $toString($requireObjectCoercible(inputArg));    }    /**     * The function evaluates the passed value and converts it to an integer.     *     * @private     * @function     * @param {*} inputArg The object to be converted to an integer.     * @return {number} If the target value is NaN, null or undefined, 0 is     *                   returned. If the target value is false, 0 is returned     *                   and if true, 1 is returned.     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4     */    function $toInteger(inputArg) {        var number = +inputArg,            val = 0;        if ($strictEqual(number, number)) {            if (!number || number === Infinity || number === -Infinity) {                val = number;            } else {                val = (number > 0 || -1) * Math.floor(Math.abs(number));            }        }        return val;    }    /**     * The abstract operation ToLength converts its argument to an integer     * suitable for use as the length of an array-like object.     *     * @private     * @function     * @param {*} inputArg The object to be converted to a length.     * @return {number} If len <= +0 then +0 else if len is +INFINITY then     *                   2^53-1 else min(len, 2^53-1).     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength     */    function $toLength(inputArg) {        return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);    }    if (!String.prototype.toChunks) {        /**         * This method chunks a string into an array of strings of a specified         * chunk size.         *         * @function         * @this {string} The string to be chunked.         * @param {Number} chunkSize The size of the chunks that the string will         *                           be chunked into.         * @returns {Array} Returns an array of the chunked string.         */        $defineProperty(String.prototype, 'toChunks', {            enumerable: false,            configurable: true,            writable: true,            value: function (chunkSize) {                var str = $onlyCoercibleToString(this),                    chunkLength = $toInteger(chunkSize),                    chunked = [],                    numChunks,                    length,                    index,                    start,                    end;                if (chunkLength < 1) {                    return chunked;                }                length = $toLength(str.length);                numChunks = Math.ceil(length / chunkLength);                index = 0;                start = 0;                end = chunkLength;                chunked.length = numChunks;                while (index < numChunks) {                    chunked[index] = str.slice(start, end);                    start = end;                    end += chunkLength;                    index += 1;                }                return chunked;            }        });    }}());/* * Some tests */(function () {    'use strict';    var pre = document.getElementById('out'),        chunkSizes = [],        maxChunkSize = 512,        testString = '',        maxTestString = 100000,        chunkSize = 0,        index = 1;    while (chunkSize < maxChunkSize) {        chunkSize = Math.pow(2, index);        chunkSizes.push(chunkSize);        index += 1;    }    index = 0;    while (index < maxTestString) {        testString += String.fromCharCode(Math.floor(Math.random() * 95) + 32);        index += 1;    }    function log(result) {        pre.appendChild(document.createTextNode(result + '\n'));    }    function test() {        var strLength = testString.length,            czLength = chunkSizes.length,            czIndex = 0,            czValue,            result,            numChunks,            pass;        while (czIndex < czLength) {            czValue = chunkSizes[czIndex];            numChunks = Math.ceil(strLength / czValue);            result = testString.toChunks(czValue);            czIndex += 1;            log('chunksize: ' + czValue);            log(' Number of chunks:');            log('  Calculated: ' + numChunks);            log('  Actual:' + result.length);            pass = result.length === numChunks;            log(' First chunk size: ' + result[0].length);            pass = pass && result[0].length === czValue;            log(' Passed: ' + pass);            log('');        }    }    test();    log('');    log('Simple test result');    log('abcdefghijklmnopqrstuvwxyz'.toChunks(3));}());
<pre id="out"></pre>

#12


0  

    window.format = function(b, a) {        if (!b || isNaN(+a)) return a;        var a = b.charAt(0) == "-" ? -a : +a,            j = a < 0 ? a = -a : 0,            e = b.match(/[^\d\-\+#]/g),            h = e && e[e.length - 1] || ".",            e = e && e[1] && e[0] || ",",            b = b.split(h),            a = a.toFixed(b[1] && b[1].length),            a = +a + "",            d = b[1] && b[1].lastIndexOf("0"),            c = a.split(".");        if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1);        d = b[0].split(e);        b[0] = d.join("");        var f = b[0] && b[0].indexOf("0");        if (f > -1)            for (; c[0].length < b[0].length - f;) c[0] = "0" + c[0];        else +c[0] == 0 && (c[0] = "");        a = a.split(".");        a[0] = c[0];        if (c = d[1] && d[d.length -                1].length) {            for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e);            a[0] = f        }        a[1] = b[1] && a[1] ? h + a[1] : "";        return (j ? "-" : "") + a[0] + a[1]    };var str="1234567890";var formatstr=format( "##,###.", str);alert(formatstr);This will split the string in reverse order with comma separated after 3 char's. If you want you can change the position.

#13


0  

Using slice() method:

使用切片()方法:

function returnChunksArray(str, chunkSize) {  var arr = [];  while(str !== '') {    arr.push(str.slice(0, chunkSize));    str = str.slice(chunkSize);  }  return arr;}

The same can be done using substring() method.

使用substring()方法也可以这样做。

function returnChunksArray(str, chunkSize) {  var arr = [];  while(str !== '') {    arr.push(str.substring(0, chunkSize));    str = str.substring(chunkSize);  }  return arr;}

#14


0  

What about this small piece of code:

这一小段代码:

function splitME(str, size) {    let subStr = new RegExp('.{1,' + size + '}', 'g');    return str.match(subStr);};

#15


-1  

function chunkString(str, length = 10) {    let result = [],        offset = 0;    if (str.length <= length) return result.push(str) && result;    while (offset < str.length) {        result.push(str.substr(offset, length));        offset += length;    }    return result;}