Extend selection to whole words

There is an old post here but it doesnt seem to work (esp when it comes to larger docs with multiple levels of nesting/entities etc.

What I want to do is this: when user selects a range, I want to “extend” the selection to have full words. For eg, if you selected a part of this sentence, but began in the middle of a word and/or ended in the middle of a word, I want to extend that selection to fill whole words (so, start of the word at the start of selection and end of the word at the end of selection).

I’m able to achieve this with a custom function to create a selection but it only works for simple paragraphs. The moment headings, horizontal lines, paragraphs inside blockquotes etc get involved, it doesnt work.

Any pointers?