How to split a string into specific Javascript sizes?

Asked

Viewed 1,240 times

8

I need to share a string in specific Javascript size.

I know it’s possible to use the Join to transform a string in a array letter:

'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 divide the string every three.

str_split ('stackoverflow', 3)

Upshot:

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

Is there any way to do this in Javascript?

5 answers

14


The simplest way is:

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

jsFiddle: https://jsfiddle.net/1qhjtc66/1/

The way without Regex 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: https://jsfiddle.net/58ckfs2f/

Another way, integrating the @Maniero response in a role would:

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: https://jsfiddle.net/p5611mnw/


And which is the fastest?

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

match 208 ms
pushloop 388 ms
substring 30 ms

9

I know someone will provide a solution with Regex, but I prefer something like this (can put in a function to then 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]);

I put in the Github for future reference.

  • Ah, it’s true! You can use the substring also :D

4

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

3

I always like to write the codes in ES5/ES6 versions, as well as their mandatory 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, updated with the model proposed here, the result ended up being:

match 328 ms
pushloop 260 ms
substring 31 ms
splitStr 110 ms

0

There’s n ways of doing, another way would be like this:

var string = 'stackoverflow';

fnc = (str, num) => {
    var t=str.split(''), col = [];
    for(var i in t) {
       col.push(t[i]);
       if((i+1) % num === 0) {
         col.push('-');
       } 
    } 
  return col.join('').split('-').filter(e => e != "");
}

fnc(string, 3);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.