简体   繁体   English

你如何在javascript中的某些字符数字处拆分字符串?

[英]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() ? 你会用.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"] 结果是数组: ["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; 这是一个使用while循环的简单方法;

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: 如果您不想使用RegExp,您也可以这样做:

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. 如果你想切断任何剩余部分,更换Math.ceilMath.floor电话。

Understanding: 理解:

This function creates an Array with the length of the number of slices, containing the expected parts of the text. 此函数创建一个Array,其长度为切片数,包含文本的预期部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM