React Guy
React Guy

Reputation: 35

Insert comma after characters in JavaScript

I am trying to add comma after some character length but I am failed because my case is different . What I want to achieve I want to insert comma after character length like (1,23,433,4444,55555) upto. If for example character is ( 123 ) . Then I want to insert comma after 1 ( 1,23 ) . If characters is (123433) then I want to insert comma (1,23,433) . Could someone please help me how to resolve this issue .

Thanks

Code

Convert = (x) => {
    x = x.toString()
    var lastThree = x.substring(x.length - 2)
    var otherNumbers = x.substring(0, x.length - 3)
    if (otherNumbers != '') lastThree = ',' + lastThree
    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ',') + lastThree
    return res
  }

Upvotes: 0

Views: 1381

Answers (2)

Aditya Menon
Aditya Menon

Reputation: 774

You could also try this:

testCase = '123433444455555';

let convert = ([...x]) => {
  let i = 1, subStrings = [];

  while (x.length) {
    subStrings.push(x.splice(0, i).join(""));
    i += 1;
  }

  return subStrings.join(",")
}

let result = convert(testCase);
console.log(result);

Making use of Array.splice we will make an intermediate array of substrings of increasing length. Splice will return the entire string if you attempt to splice more than the current length.

Once the number has been split up appropriately we simply join it with , and return the result.

Upvotes: 3

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

You can do the following,

a = '123433444455555';

const convert = (str) => {
  let step = 1;
  let end = 0;
  while(end + step < str.length -1) {
    str = [str.slice(0, end+step), ',', str.slice(end+step)].join('');
    step++;
    end = end + step;
  }
  return str;
}
let ret = convert(a);
console.log(ret);

Upvotes: 2

Related Questions