将字符串分组为n个字符的块并应用替换

时间:2016-05-12 17:13:21

标签: javascript

此代码需要" AK345KJ"并尝试取回[" A K 3"," 4 5 K"," J"]但浏览器在数组的所有项目中都未定义。不知道为什么。感谢

x = "AK345KJ"
x.match(/.{1,3}/g).map(function(item) {item.replace(""," "); console.log(item)})

2 个答案:

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