-1

I am trying to take input from the user and insert commas after every number. For example if the user types 12345 I want the result to be 1,2,3,4,5. Could someone please help me how to resolve this issue?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Jonas
  • 261
  • 1
  • 3
  • 13
  • https://stackoverflow.com/questions/5269856/how-to-split-comma-separated-string-using-javascript – Dennis Vash Jul 16 '20 at 16:35
  • it actually work for me but it just add comma to number, I want comma in alphabetic too . `value && value.replace(/\B(?=(\d{1})+(?!\d))/g, ","); ` – Jonas Jul 16 '20 at 17:22

3 Answers3

1

You can use spread syntax and Array#join.

const str = "12345";
const res = [...str].join();
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • it actually work for me but it just add comma to number, I want comma in alphabetic too . `value && value.replace(/\B(?=(\d{1})+(?!\d))/g, ","); ` – Jonas Jul 16 '20 at 17:22
  • @Jonas What do you mean by that? – Unmitigated Jul 16 '20 at 17:22
  • @hav1 . I mean to say that it add comma to the end of every character but it just work for number , I want to add comma in alphabetic character tooo – Jonas Jul 16 '20 at 17:25
  • @Jonas How does it not work for alphabetic characters? https://jsfiddle.net/wrgkq32d/ – Unmitigated Jul 16 '20 at 17:27
  • Could you please check this question https://stackoverflow.com/questions/62941948/how-to-add-event-listener-to-redux-form – Jonas Jul 16 '20 at 19:32
1

this example will help understand how to split the value entered

r = document.getElementById("result")
btn = document.getElementById("btn")

btn.addEventListener("click", () => {
  v = document.getElementById("values").value
  var splitv = v.split("").join(",")
  console.log(splitv)
  r.textContent = splitv
})
<label>enter values</label>
<input id="values" />
<div id="result"></div>
<br>
<button id=btn>result</button>
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

Convert it onBlur or onSubmit

function addCommas (num) {
  return num.toString().split("").join(",");
}

console.log(addCommas(12345)); 
Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14
  • Actually , it work but I need to be use it in redux form . Could you please help me – Jonas Jul 16 '20 at 17:07
  • it actually work for me but it just add comma to number, I want comma in alphabetic too . `value && value.replace(/\B(?=(\d{1})+(?!\d))/g, ",");` – Jonas Jul 16 '20 at 17:22