i have this number 1234567890
this is how i want to display it
1234 567 890
im trying this
console.log('1234567899'.replace(/(\d)(?=(\d{3})+$)/g, '$1 '));
i have this number 1234567890
this is how i want to display it
1234 567 890
im trying this
console.log('1234567899'.replace(/(\d)(?=(\d{3})+$)/g, '$1 '));
One option would be to have an optional group that starts at the beginning of the string and (greedily) matches the number of the leading-digits-without-commas you want to have. Then, instead of replacing with just \1, replace with \1\2 (the optional group plus the second captured digits):
const format = str => str.replace(
/(^(?:\d{1,2}))?(\d{1,3})(?=(?:\d{3})+$)/g,
// ^^^ change these to change the number of unbroken leading digits
'$1$2 '
);
console.log(format('1234567899'));
console.log(format('01234567899'));
console.log(format('101234567899'));
The above snippet's optional group begins with \d{1,2}, which means that there will be between 3 and 5 leading digits, unbroken by commas. To change that quantity, just change the number of repetitions.
The leading group (^(?:\d{1,2}))? means: optionally, the beginning of the string, followed by one or two digits.
Try with this
var str = "1234567890";
var temp = str.substring(0,4); // get first 4 digits
//Add space after 3 digits. You can use same logic to add space after 4 digits as well
var z = [...str.substring(4)].map((d, i) => i % 3 == 0 ? ' '+d : d).join('').trim();
//Concatenate both strings
var result = temp + ' ' + z;
//Display result
console.log(temp);
console.log(z);
console.log(result);
Try this regex which ensures the numbers will be grouped in bunches of three except the first digits which can be grouped from four to five.
Match /(^\d{4}|\d{3})(?=(\d{3})*$)/g and replace with $1
Here is some sample javascript code,
console.log('1234567899' + ' --> ' + '1234567899'.replace(/(^\d{4}|\d{3})(?=(\d{3})*$)/g, '$1 '));
console.log('12345678991' + ' --> ' + '12345678991'.replace(/(^\d{4}|\d{3})(?=(\d{3})*$)/g, '$1 '));
console.log('123456789912' + ' --> ' + '123456789912'.replace(/(^\d{4}|\d{3})(?=(\d{3})*$)/g, '$1 '));
console.log('1234567899123' + ' --> ' + '1234567899123'.replace(/(^\d{4}|\d{3})(?=(\d{3})*$)/g, '$1 '));