How i can add comma after each entered number only

Viewed 103

How can i add comma automatically after each entered number. For example like : 1,2,3,4

If i add number 5 after 4 so it should be separated with the comma. Below is my code.

function addComma(txt) {
    txt.value = txt.value.replace(",", "").replace(/(\d+)(\d{3})/, "$1,$2");
}
<input type="text" id="txt" onkeyup="addComma(this);" />

the comma is separating after a few numbers. I require an auto-add comma after each number has been entered.

1 Answers

I change your RegEx. See below example.

function addComma(txt) {
    txt.value = txt.value.replace(/(\d)(?=(\d)+(?!\d))/g, "$1,");
}
<input type="text" id="txt" onkeyup="addComma(this);" />

Related