How to split a string into specific sizes in JavaScript?

4

I need to split a string into a specific size in JavaScript.

I know you can use Join to turn a string into a array of letters:

'hello'.split('')

However, I need a way where I can determine the size at which this string will be broken.

For example, in PHP, we have the function str_split where you can determine the size of these strings .

In the example below, I want to break the string by 3 in 3.

str_split ('stackoverflow', 3)

Result:

[
    "sta",
    "cko",
    "ver",
    "flo",
    "w",
]

Is there any way to do this in JavaScript?

    
asked by anonymous 11.08.2016 / 14:59

4 answers

10

The simplest way is:

'string'.match(/.{1,3}/g)

jsFiddle: link

The non-regexed way with a loop can be

const string = 'stackoverflow';
function spliter(str) {
    const chars = str.split('');
    let temp = [];
    let parts = [];
    for (let char of chars) {
        temp.push(char);
        if (temp.length == 3) {
            parts.push(temp.join(''));
            temp = [];
        }
    }
    if (temp.length) parts.push(temp.join(''));
    return parts;
}

jsFiddle: link

Another way, integrating the @bigown response into a function would be:

const string = 'stackoverflow';

function spliter(str, nr) {
    const parts = [];
    for (let i = 0, length = str.length; i < length; i += nr) {
        parts.push(str.substring(i, i + nr));
    }
    return parts;
}

console.log(spliter(string, 3)); // ["sta", "cko", "ver", "flo", "w"]
console.log(spliter(string, 2)); // ["st", "ac", "ko", "ve", "rf", "lo", "w"]
console.log(spliter(string, 5)); // ["stack", "overf", "low"]

jsFiddle: link

And which is the fastest?

I ran a test where I run the function 100,000 times and the result was:

match 208 ms
pushloop 388 ms
substring 30 ms
    
11.08.2016 / 15:07
7

I know that someone will provide a solution with RegEx, but I prefer something like that (you can go into a function to later use in a single line in a simpler way than RegEx and probably faster.

var str = 'stackoverflow';
var chunks = [];

for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
    chunks.push(str.substring(i, i + 3));
}
for (var i = 0; i < chunks.length; i++) {
    console.log(chunks[i]);
}
    
11.08.2016 / 15:06
2

string.match

console.log("stackoverflow".match(/.{1,3}/g));

Array.map

var str = 'stackoverflow';
var partes = 3
var pedacos = []

str.split('').map(function(v, i){
    var len = str.length - 1

    if ((i % partes == 0) && (len !== i))
      pedacos.push(str.substring(i, i + partes))
    
    if (len == i)
      pedacos.push(v)
})

console.log(pedacos)

While / substring

function extrairPedacos(str, n){
    var pedacos = []
    var i = 0
    
    while (i < str.length){
      (i % n == 0 ? pedacos.push(str.substring(i, i + n)) : i++)
      i++
    }
    return pedacos
}

console.log(extrairPedacos("stackoverflow", 3))
    
11.08.2016 / 15:06
1

I always like to write the codes in ES5 / ES6 versions, as well as their imperative and functional versions, so to contribute here is a somewhat functional ES6 model:

const splitStr = (str, size) => {
  const length = Math.ceil(str.length / size);
  return Array.from({ length }, (_, i) => (i *= size, str.substring(i, i + size)))
}

Taking advantage of Sergio's test, I updated with the proposed model here, the result ended up being:

match 328 ms
pushloop 260 ms
substring 31 ms
splitStr 110 ms
    
11.08.2016 / 18:40