How do we split a string every 3 characters from the back using JavaScript?
Say, I have this:
str = 9139328238
after the desired function, it would become:
parts = ['9','139','328','238']
How do we do this elegantly?
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To split a string every n characters: Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
I know this is an old question, but I would like to provide my own one-line version to solve the problem :)
"12345678".split('').reverse().join('').match(/.{1,3}/g).map(function(x){
return x.split('').reverse().join('')
}).reverse()
This basically reverses the string, captures the groups of 3 elements, reverses each group and then reverses the whole string.
The steps are:
"12345678" -> [1, 2, 3, 4, 5, 6, 7, 8] //.split('')
[1, 2, 3, 4, 5, 6, 7, 8] -> [8, 7, 6, 5, 4, 3, 2, 1] //.reverse()
[8, 7, 6, 5, 4, 3, 2, 1] -> "87654321" //.join('')
"87654321" -> [876, 543, 21] //.match(...)
[876, 543, 21] -> [678, 345, 12] //.map(function(x){...})
[678, 345, 12] -> [12, 345, 678] //.reverse()
You can then join the array with a character (e.g. the ',' for thousands separator)
[12, 345, 678].join(',') -> "12,345,678"
var myString = String( 9139328238 );
console.log( myString.split( /(?=(?:...)*$)/ ) );
// ["9", "139", "328", "238"]
I can't make any performance guarantees. For smallish strings it should be fine.
Here's a loop implementation:
function funkyStringSplit( s )
{
var i = s.length % 3;
var parts = i ? [ s.substr( 0, i ) ] : [];
for( ; i < s.length ; i += 3 )
{
parts.push( s.substr( i, 3 ) );
}
return parts;
}
There are a lot of complicated answers here.
function group(value) {
return value.match(/\d{1,3}(?=(\d{3})*$)/g);
}
console.log(group('1'));
console.log(group('123'));
console.log(group('1234'));
console.log(group('12345'));
console.log(group('123456'));
console.log(group('1234567'));
console.log(group('12345678'));
console.log(group('123456789'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With