chromedude
chromedude

Reputation: 4302

How do you split a string at certain character numbers in javascript?

I want a string split at every single character and put into an array. The string is:

var string = "hello";

Would you use the .split() ? If so how?

Upvotes: 4

Views: 9000

Answers (7)

niieani
niieani

Reputation: 4399

If you don't want to use a RegExp, you can also do this instead:

const splitEvery = (nth) => (str) =>
  Array.from(
    {length: Math.ceil(str.length / nth)},
    (_, index) => str.slice(index * nth, (index + 1) * nth)
  )

// example usage:
const splitEvery2nd = splitEvery(2)
const result = splitEvery2nd('hello')
// result is: ['he', 'll', 'o']

If you want to cut off any remaining parts, replace the Math.ceil with a Math.floor call.

Understanding:

This function creates an Array with the length of the number of slices, containing the expected parts of the text.

Upvotes: 0

Sean Kinsey
Sean Kinsey

Reputation: 38046

If you want it short and 'functional':

var input = 'abcdefghijklmn1234567890';
var arr = Array.prototype.slice.call(input), output = [];
while (arr.length) output.push(arr.splice(0, 3).join(''));

output; // ["abc", "def", "ghi", "jkl", "mn1", "234", "567", "890"]

Upvotes: 0

Sdedelbrock
Sdedelbrock

Reputation: 5292

Here is a simple way do it with a while loop;

function splitStringAtInterval(str, len){
var len = 10;
var arr = [];
str = str.split("");
while(str.length > len){
    arr.push(str.splice(position,len).join(""));
}
if(str.length > 0)arr.push(str.join(""));
    return arr;
}

Upvotes: 0

Gary
Gary

Reputation: 101

I was researching a similar problem.. to break on every other character. After reading up on regex, I came up with this:

data = "0102034455dola";
arr = data.match(/../g);

The result is the array: ["01","02","03","44","55","do","la"]

Upvotes: 10

rob
rob

Reputation: 10119

If you really want to do it as described in the title, this should work:

function splitStringAtInterval (string, interval) {
var result = [];
for (var i=0; i<string.length; i+=interval)
  result.push(string.substring (i, i+interval));
return result;
}

Upvotes: 5

Dustin Laine
Dustin Laine

Reputation: 38503

var s= "hello";
s.split("");

Upvotes: 1

Harmen
Harmen

Reputation: 22438

Yes, you could use:

var str = "hello";

// returns ["h", "e", "l", "l", "o"]
var arr = str.split( '' ); 

Upvotes: 8

Related Questions