JSFiddle - React, Tailwind, and code Playground
HTML
<p>Click on the text field, then press the left and right arrow keys.</p>
<input type='text' id='humantext' class='form-control' value='foo bar and bar bar foo, a bar fooey foo foo bar' />
JavaScript
$(document).ready(function () {
function cursor(el) {
var val = el.value;
return val.slice(0, el.selectionStart).length;
}
$("#humantext").keydown(function (e) {
var words = $(this).val().split(' ');
var chars = $(this).val();
var humantext = document.getElementById('humantext');
var position = cursor(humantext);
var startChar = false, endChar = false;
var selectedLength = (humantext.selectionEnd - humantext.selectionStart);
if (e.keyCode == 37) {
e.preventDefault();
for(x=position;x > 0;x--)
{
if((chars[x]==' ') && (endChar) && (!startChar)) {startChar = x;}
if((chars[x]==' ') && (!endChar)) {endChar = x;}
if((startChar !== false) && (endChar !== false)) break;
}
if((!selectedLength) && (position==chars.length)) {startChar = endChar; endChar = chars.length;}
if(startChar != 0) startChar++;
humantext.setSelectionRange(startChar, endChar);
}
if (e.keyCode == 39) {
e.preventDefault();
for(x=position;x < chars.length;x++)
{
if((chars[x]==' ') && (startChar) && (!endChar)) {endChar = x;}
if((chars[x]==' ') && (!startChar)) {startChar = x;}
if((startChar !== false) && (endChar !== false)) break;
}
if(!endChar) endChar = chars.length;
if(!startChar) startChar = chars.length;
if((!selectedLength) && (position==0)) {console.log('ZORRP'); endChar = startChar; startChar = 0;}
if(chars[startChar] == ' ') startChar++;
humantext.setSelectionRange(startChar, endChar);
}
});
});