Fred J. Fred J. - 5 months ago 7x
Javascript Question

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


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