JSFiddle - React, Tailwind, and code Playground
by Felipe Alfaro
HTML
<div id="content" onmouseup="splitText()">
<div>hello-1 hello-2</div>
<div>hello-2.5</div>
<div>hello-3 hello-4 yeah</div>
<div>hello hello</div>
<div>hello hello</div>
<div>hello hello</div>
</div>
CSS
#content div {
position: unset;
}
JavaScript
function splitText() {
let element = document.getElementById("content")
if (window.getSelection) {
let selection = window.getSelection()
let selectionText = selection.toString()
if (selection.rangeCount) {
let range = selection.getRangeAt(0)
let precedingRange = document.createRange()
precedingRange.setStartBefore(element.firstChild)
precedingRange.setEnd(range.startContainer, range.startOffset)
let textPrecedingSelection = precedingRange.toString()
let wordIndex = textPrecedingSelection.split(/\s+/).length - 2
let fullText = element.innerText
let currentWordIndex = -1
let previousWords = []
let selectionFirstMatching = []
fullText.split(' ').filter(word => !!word).forEach((word, i) => {
let isPrev = true
word.split('\n').forEach(wordInWord => {
currentWordIndex++
if ((currentWordIndex >= wordIndex) && isPrev)
isPrev = false
})
if (isPrev)
previousWords.push(word)
else
selectionFirstMatching.push(word)
})
let splittedContent = selectionFirstMatching.join(' ').split(selectionText)
let previousContent = [...previousWords, splittedContent.shift()].join(' ')
let nextContent = splittedContent.join(selectionText)
return [previousContent, selectionText, nextContent]
}
}
}