Skip to content

Instantly share code, notes, and snippets.

@DenisDov
Last active October 22, 2020 15:08
Show Gist options
  • Save DenisDov/2101cf89c34c498566587878bda88beb to your computer and use it in GitHub Desktop.
Save DenisDov/2101cf89c34c498566587878bda88beb to your computer and use it in GitHub Desktop.
Insert commas between numbers after paste into input
function dividePastedValuesByCommas(e) {
/* bind on paste event */
e.preventDefault();
const target = e.target,
val = target.value,
start = target.selectionStart,
arr = e.originalEvent.clipboardData
.getData('text')
.replace(/\r\n\t|\n|\r\t|\s|,|;/gm, ' ')
.split(' ')
.filter((item) => Boolean(item.trim()))
.map((elem) => elem.trim().replace(/\D/gim, ''))
.join(', ');
target.value = val.substring(0, start) + arr + val.substring(target.selectionEnd, val.length);
let pos = val ? start + arr.length : target.value.length;
target.setSelectionRange(pos, pos);
target.dispatchEvent(new Event('input'));
}
$(document).on('paste', '#input', dividePastedValuesByCommas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment