JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" class="singleSpace" />
JavaScript
$('.singleSpace').keyup(function() {
var foo = this.value.replace(/^( *)([^ ] *)(.*)/g, function(a,b,c,d,e){
return $.trim(c) + ' ' + d.replace(/ /g, '').slice(0,40);
})
var carretPos = doGetCaretPosition(this)
carretPos += foo.length - this.value.length
this.value = foo;
setSelectionRange(this, carretPos, carretPos)
});
//Code taken from
// http://stackoverflow.com/questions/17858174/set-cursor-to-specific-position-on-specific-line-in-a-textarea
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
//Code taken from
// http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
...