0

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(',')
}
5
  • You can splice the last three digits first, add commas after every two digit, then concatenate the last three digits you spliced in the beginning Commented Dec 17, 2020 at 11:16
  • Could you please try simple example Commented Dec 17, 2020 at 11:16
  • 1
    What is the input to your function? Commented Dec 17, 2020 at 11:20
  • let suppose value is 34898934984 Commented Dec 17, 2020 at 11:21
  • @ReactGuy I did try a simple example. However, for any case, you have to make sure your string length is 3 + 2x, where x is an integer bigger than 0 Commented Dec 17, 2020 at 12:02

4 Answers 4

2

You could replace with positive lookahead of wanted groups.

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

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

343434434544 , Could you please try this value I am getting result 34,34,34,434,544
I need something like 34,34,34,43,454
0
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]))

Comments

0

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

Comments

0

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("")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.