Skip to content

Instantly share code, notes, and snippets.

@macedd
Last active August 29, 2015 14:23
Show Gist options
  • Save macedd/85d787e9a436ca19969d to your computer and use it in GitHub Desktop.
Save macedd/85d787e9a436ca19969d to your computer and use it in GitHub Desktop.
remove duplicate spaces from field while typing
$('textarea').on('keyup', function() {
// store cursor location
var start = this.selectionStart,
end = this.selectionEnd,
len = this.value.length;
// remove duplicate spaces from field
$(this).val(
this.value.trim()
.replace(/(\n\n)+/g, '\n')
.replace(/(\s\s)+/g, ' ')
);
try {
// calculate new cursor location
var diff = len - this.value.length;
start = start-diff; if (start < 0) start = 0;
end = end-diff; if (end < 0) end = 0;
// set new cursor position
this.setSelectionRange(start, end);
} catch (e) {}
});
Initial workout for development / prototype
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment