Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将字符串拆分为若干部分的操作_Javascript - Fatal编程技术网

Javascript 将字符串拆分为若干部分的操作

Javascript 将字符串拆分为若干部分的操作,javascript,Javascript,在得到字符串123456789之后,我想显示类型是123456789。我使用了下面的方法,但我不认为这是一个伟大的方法,所以有人有更好的方法吗 let num = '123456789' let result = num.slice(0,3)+ ' '+num.slice(3,6)+ ' '+num.slice(6,9) // result = '123 456 789' 您可以使用全局正则表达式和匹配3位数字,然后用空格连接: let num='123456789'; const resu

在得到字符串123456789之后,我想显示类型是123456789。我使用了下面的方法,但我不认为这是一个伟大的方法,所以有人有更好的方法吗

let num = '123456789'
let result = num.slice(0,3)+ ' '+num.slice(3,6)+ ' '+num.slice(6,9) // result = '123 456 789'

您可以使用全局正则表达式和
匹配
3位数字,然后用空格连接:

let num='123456789';
const result=num
.match(/\d{3}/g)
.加入(“”);

控制台日志(结果)您可以使用while循环和
slice()

let str='123456789';
函数拆分方式(str,num){
让结果=“”;
while(str.length>num){
结果+=str.slice(0,3)+'';
str=str.slice(3);
}
返回结果+str;
}
console.log(splitBy(str,3))您可以使用根据提供的分割长度返回块数组。然后使用来连接它们

let num='123456789'
函数getChunks(字符串,n){
const length=Math.ceil(string.length/n);
返回Array.from({length},(u,i)=>string.slice(i*n,(i+1)*n))
}
log(getChunks(num,3.join(“”))
log(getChunks(num,4).join(“”))
清除重复的