-1

I want to show the type is 123 456 789 after I get the string 123456789. I used the method like following, but I do not think it is a great way, so does anyone has a better way ?

let num = '123456789'
let result = num.slice(0,3)+ ' '+num.slice(3,6)+ ' '+num.slice(6,9) // result = '123 456 789'
Yummy
  • 33
  • 4
  • 3
    Clear duplicate of [Javascript elegant way to split string into segments n characters long](https://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long) – Blue Mar 04 '19 at 07:31

3 Answers3

6

You can use a global regular expression and match 3 digits, then join by spaces:

let num = '123456789';
const result = num
  .match(/\d{3}/g)
  .join(' ');
console.log(result);

Or, with .replace and lookahead for another digit:

let num = '123456789';
const result = num.replace(/\d{3}(?=\d)/g, '$& ');
console.log(result);
Snow
  • 3,820
  • 3
  • 13
  • 39
0

You do that using while loop and slice()

let str = '123456789';
function splitBy(str,num){
  let result = '';
  while(str.length > num){
    result += str.slice(0,3) + ' ';
    str = str.slice(3);
  }
  return result + str;
}
console.log(splitBy(str,3));
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use Array.from() to return an array of chunks based on the split-length provided. Then use join() to concatenate them

let num = '123456789'

function getChunks(string, n) {
  const length = Math.ceil(string.length / n);
  return Array.from({ length }, (_, i) => string.slice(i * n, (i + 1) * n))
}

console.log(getChunks(num, 3).join(' '))
console.log(getChunks(num, 4).join(' '))
adiga
  • 34,372
  • 9
  • 61
  • 83