Insert comma after every two digits in JavaScript

1k Views Asked by At

I have a case where I want to insert two commas after every two digits instead of the last three digits I want to add one comma. The result will look like this ( 34,34,54,388 ). Could someone please help me with how to resolve this issue?

Code

export const newPriceFormatConverter = ([...x]) => {
  let i = 2,
    subStrings = []

  while (x.length) {
    subStrings.push(x.splice(0, i).join(''))
  i+=2
  }

  return subStrings.join(',')
}
4

There are 4 best solutions below

2
On

You could replace with positive lookahead of wanted groups.

const
    string = '343434434544',
    result = string.replace(/.(?=(..)*...$)/g, '$&,');

console.log(result);

0
On
const setComma = (arr) => {
  let result = ''

  for (let i = 0; i < arr.length; i++) {
    if ((i + 1) % 2 === 0 && i < arr.length - 2) {
      result = result + arr[i] + ','
    } else {
      result = result + arr[i]
    }
  }
  return result
}

console.log(setComma([...str]))
0
On

Assuming that you want to convert integer / integer as string.

function convert(front)
{
  var result="";
  front=front.toString().split("");
  var end=front.splice(-3);
  while(front.length>0)
  {
    result+=`${front.splice(0,2).join("")},`;
  }
  result=`${result}${end.join("")}`;
  console.log(result);
}

convert(1);
convert(12);
convert(123);
convert(1234);
convert(12345);
convert(123456);
convert(1234567);
convert(12345678);
convert(123456789);
convert(1234567890);

0
On

You can try something like this:

let str = '34898934984'
console.log(foo([...str]))

function foo(strArray){
const toBeConcatenated = strArray.splice(strArray.length-3,3);
const newStrArray = [...strArray]

for(let i = newStrArray.length; i >1; i--){
  if(i%2 == 0) newStrArray.splice(i,0,',')
}

return newStrArray.join("") + toBeConcatenated.join("")
}