如何在 Javascript 中以特定间隔将字符串拆分为数组
How to split strings at specific intervals to arrays in Javascript
如何在Javascript中以特定的间隔将字符串拆分为数组?
例如:将此字符串拆分为 4 个字符(包括空格和字符)
this is an example should be split,numbers(123),space,characters also included
自
this ------> 1st array
is ------> 2nd array
an ------> 3rd array
exam ------> 4th array
ple ------> 5th array
shou ------> 6th array ............ etc till.....
..ed ------> last array
试试这个:
var foo = "this is an example should be split,numbers(123),space,characters also included";
var arr = [];
for (var i = 0; i < foo.length; i++) {
if (i % 4 == 0 && i != 0)
arr.push(foo.substring(i - 4, i));
if (i == foo.length - 1)
arr.push(foo.substring(i - (i % 4), i+1));
}
document.write(arr);
console.log(arr);
下面是一个函数,可以将字符串拆分为所需大小的块:
function splitN(s, n) {
var output = [];
for (var i = 0; i < s.length; i+=4) {
output.push(s.substr(i, 4));
}
return(output);
}
你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/JvabJ/
将上面代码中的"4"更改为"n":
function splitN(s, n) {
var output = [];
for (var i = 0; i < s.length; i+=n) {
output.push(s.substr(i, n));
}
return(output);
}
您可以将match
与正则表达式一起使用:
console.log("this is an example should be split,numbers(123),space,characters also included".match(/.{1,4}/g));
相关文章:
- 将字符串拆分为数组时出现JavaScript错误
- 如何将字符串拆分为字符,但在javascript中保留空格
- 将字符串拆分为;只要它's不在»«
- 如何将以下字符串拆分为二维数组:
- 将javascript中的字符串拆分为一个数组
- 这个字符串拆分器可以重构或改进吗
- Regex将字符串拆分为大小适中的块
- 将字符串拆分为具有固定字符数的数组
- 将字符串拆分为数组
- 如何在没有javascript中的split函数的情况下将字符串拆分为单词
- 字符串拆分并获取第一次和最后一次出现
- node.js将接收到的字符串拆分为不同的变量,然后格式化为json字符串
- 如何将复杂的字符串拆分为多个部分
- 将字符串拆分为多维数组
- 将逗号分隔的字符串拆分为单独的字符串
- 如何在 Javascript 中以特定间隔将字符串拆分为数组
- Javascript 字符串拆分
- 使用 jQuery 将长字符串拆分为文本块
- 在javascript中将字符串拆分为句子
- 在将字符串拆分为硒时获取空输出