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



此代码使用"AK345KJ"并试图返回["A K 3"、"4 5 K"、"J"],但浏览器在数组的所有项中都给出了未定义的值。不知道为什么。感谢

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

您的.map应该返回,添加空格的方式略有不同。

你可能想要这样的东西:

x.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');})
// ["A K 3", "4 5 K", "J"]

使用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));

使用映射函数(如乌兹别克斯坦的回答所示),整个想法可以归结为两条线:

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(' ');}));

最新更新