Fred J.
Fred J.

Reputation: 6039

Group string in chunks of n characters and apply replace

This code takes "AK345KJ" and tries to get back ["A K 3", "4 5 K", "J"] but the browser is giving undefined in all items of the array. Not sure why. Thanks

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

Upvotes: 0

Views: 35

Answers (2)

Ani Menon
Ani Menon

Reputation: 28239

Using match() :

var a = "AK345KJ"
var b = a.match(/(.{1,3})/g);
alert(b);

Snippet:

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

Using the map function (as shown in Uzbekjon's answer), This whole think can be reduced to two lines :

var a = "AK345KJ"
alert(a.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');}));

Snippet :

var a = "AK345KJ"
alert(a.match(/.{1,3}/g).map(function(item) {return item.split('').join(' ');}));

Upvotes: 1

Uzbekjon
Uzbekjon

Reputation: 11813

Your .map should return and adding spaces is done slightly differently.

You probably want something like this:

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

Upvotes: 1

Related Questions