开发者

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

开发者 https://www.devze.com 2023-01-21 17:34 出处:网络
I want a string split at every single character and put into an array. The string is: var string = \"hello\";

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

var string = "hello";

Would 开发者_JS百科you use the .split() ? If so how?


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"]


Yes, you could use:

var str = "hello";

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


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;
}


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


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;
}


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"]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号