Last active
October 22, 2020 15:08
-
-
Save DenisDov/2101cf89c34c498566587878bda88beb to your computer and use it in GitHub Desktop.
Insert commas between numbers after paste into input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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