此代码需要" AK345KJ"并尝试取回[" A K 3"," 4 5 K"," J"]但浏览器在数组的所有项目中都未定义。不知道为什么。感谢
x = "AK345KJ"
x.match(/.{1,3}/g).map(function(item) {item.replace(""," "); console.log(item)})
答案 0 :(得分:1)
使用match():
var a = "AK345KJ"
var b = a.match(/(.{1,3})/g);
alert(b);
段:
var a = "AK345KJ";
var res = "";
//to split by fixed width of 3
var b = a.match(/(.{1,3})/g);
//alert(b);
//to add spaces
for (ab in b) {
res = res + (b[ab].split('').join(' ')) + ", ";
}
//remove trailing ',' while alert
alert(res.substring(0, res.length - 2));
使用地图功能(如Uzbekjon的回答所示), 整个想法可以简化为两行:
var a = "AK345KJ"
alert(a.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');}));
摘录:
var a = "AK345KJ"
alert(a.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');}));
答案 1 :(得分:1)
您的.map
应该返回,添加空格的方式略有不同。
你可能想要这样的东西:
x.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');})
// ["A K 3", "4 5 K", "J"]