0

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
  }
2
  • Can you please explain what "after some character length" means? Do you want to increment the gap between the commas each time, like start with 1 character, then 2 characters, 3 characters and so on? Commented Dec 15, 2020 at 12:39
  • Do you want to insert commas with increasing number of digits in between them? Like for an input of 122333444455555666666 do you expect an output of 1,22,333,4444,55555,666666 Commented Dec 15, 2020 at 12:42

2 Answers 2

3

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.

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

Comments

2

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

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.