Если вы определяете «слово» как любую последовательность символов, разделенных пробелом, то вы можете просто использовать String.prototype.lastIndexOf
и String.prototype.indexOf
для поиска пробела до и после позиции курсора, а затем для получения подстроки из этого диапазона:
const inp = document.querySelector('input');
document.onselectionchange =
inp.onselect = inp.onclick = // Firefox doesn't fire selectionchange in <input>
(evt) => {
const text = inp.value;
const start_index = inp.selectionStart;
const end_index = inp.selectionEnd;
const previous_space_index = text.lastIndexOf( " ", start_index - 1 );
const next_space_index = text.indexOf( " ", end_index );
const begin = previous_space_index < 0 ? 0 : previous_space_index + 1;
const end = next_space_index < 0 ? text.length : next_space_index;
const between_spaces = text.substring( begin, end );
console.log( between_spaces );
};
<input type="text" value="this is a sentence">
Если вам действительно нужно определить «слово» как любую последовательность символов, соответствующих /\w/
, то это немного более запутанно:
const inp = document.querySelector('input');
document.onselectionchange =
inp.onselect = inp.onclick = // Firefox doesn't fire selectionchange in <input>
(evt) => {
const text = inp.value;
const start_index = inp.selectionStart;
const end_index = inp.selectionEnd;
// search in the before substring
const before_text = text.substring( 0, start_index );
// for all non word characters
const before_match = before_text.match( /\W/g );
// get the last one
const last_before_match = before_match && before_match[ before_match.length - 1 ];
// retrieve its index
const previous_nonword_index = last_before_match ? text.lastIndexOf( last_before_match, start_index - 1 ) : -1;
const begin = previous_nonword_index < 0 ? 0 : previous_nonword_index + 1;
// search in the after substring
const after_text = text.substring( end_index );
// for the first occurence of a non word character
const next_nonword_index = after_text.search( /\W/ );
// remember to add the length of the beginning string to the found index
const end = next_nonword_index < 0 ? text.length : next_nonword_index + end_index;
const between_spaces = text.substring( begin, end );
console.log( between_spaces );
};
<input type="text" value="this undefined is a sæntence wîth nøn word characters" size="40">