Fred J. Fred J. - 2 years ago 65
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)})

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download