UPDATE
If you want to insert a comma, every time you hit enter, just repair the commas using the following epxression:
/ BEGIN
(?<=\w) POSITIVE LOOKBEHIND - PRECEDED BY WORD_CHAR
\b WORD BOUNDARY
[\s,]* ZERO OR MORE - WHITE_SPACE OR COMMA_CHAR
\b WORD BOUNDARY
/ END
g FLAGS = GLOBAL
const VK_ENTER = 13
const txt = document.querySelector('#sample-text')
const insertComma = (value) => value.replace(/(?<=\w)\b[\s,]*\b/g, ' , ')
const handleEnterKey = (e) => {
var code = e.keyCode ? e.keyCode : e.which
switch (code) {
case VK_ENTER:
txt.value = insertComma(txt.value)
break
}
}
document.addEventListener('keydown', handleEnterKey)
<form autocomplete="off" onsubmit="return false;">
<input type="text" id="sample-text" value="" />
</form>
And now for something completely different…
Note: Original answer
You can listen for text input changes and swap the value by removing the present commas and re-adding them in the correct places.
For this example, if you type: "Hello 12345", the text will eventually become: "Hello 12,345"
const TYPE_AHEAD_DELAY = 0 // No delay
const SAMLE_TEXT = "Hello / 12345 / World"
let state = {
sampleText: ''
}
const main = () => {
state = createState(state) // Wrap the state in a proxy
init()
autoType('sampleText', SAMLE_TEXT, 250)
}
const processValue = (value, model) => {
switch (model) {
case 'sampleText':
return fixCommas(value)
default:
return value
}
}
const fixCommas = (value) => value
.replace(/(\d),(\d)()/g, '$1$2') // Revert commas
.replace(/(\d)(?=(\d{3})+\b)/g, '$1,') // Add commas back
const autoType = (prop, value, timeout) => {
let pos = 0, interval = setInterval(() => {
state[prop] += value[pos++]
if (pos >= value.length) {
clearInterval(interval)
}
}, timeout)
}
/* #BEGIN BOILERPLATE */
const createState = (state) => {
return new Proxy(state, {
set(target, property, value) {
target[property] = processValue(value, property)
render(property)
return true
}
})
}
const init = () => {
Object.keys(state).forEach(property => {
const input = document.querySelector(`[data-model="${property}"]`)
let timeout
input.addEventListener('keyup', (e) => {
if (TYPE_AHEAD_DELAY) {
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
listener(e)
}, TYPE_AHEAD_DELAY)
} else {
listener(e)
}
})
})
}
const listener = (event) => {
const {type, value, dataset} = event.target
state[dataset.model] = value
}
const render = (property) => {
document.querySelector(`[data-model="${property}"]`).value = state[property]
}
main()
<input type="text" data-model="sampleText" />