Skip to content Skip to sidebar Skip to footer

A Operation To Split A String To Several Part

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 ? l

Solution 1:

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

Solution 2:

You do that using while loop and slice()

let str = '123456789';
functionsplitBy(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));

Solution 3:

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'functiongetChunks(string, n) {
  const length = Math.ceil(string.length / n);
  returnArray.from({ length }, (_, i) => string.slice(i * n, (i + 1) * n))
}

console.log(getChunks(num, 3).join(' '))
console.log(getChunks(num, 4).join(' '))

Post a Comment for "A Operation To Split A String To Several Part"