There is an amazing method in class Selection
called modify()
which is created for that purpose. In my case, the solution would be:
function select() {
if (window.getSelection) {
var s = window.getSelection();
var blank = " ";
if(s == blank) {
selectBothWords(s);
}
}
}
function selectBothWords(s) {
s.modify("move", "backward", "word");
s.modify("extend", "forward", "word");
s.modify("extend", "forward", "word");
}
The function select()
checks that the selection is a 'blank space' (loosely). Then, the function selectBothWords()
uses modify to move the selection one word backwards, then, extend it two words forward.