Split text at cursor placement
by MegaScience
HTML
<input id="textInput" type="text" value="abcdefg">
<button id="checkPositionButton">Check Position</button>
<div id="informationPanel"></div>
JavaScript
// https://stackoverflow.com/a/38757490
// :: splitAt = (number, any[] | string) => [any[] | string, any[] | string]
const splitAt = (index, xs) => [xs?.slice(0, index), xs?.slice(index)]
const textInput = document.getElementById('textInput')
const informationPanel = document.getElementById('informationPanel')
function checkPosition() {
const selectionStart = textInput.selectionStart
const [before = '', after = ''] = splitAt(selectionStart, textInput.value)
informationPanel.innerHTML = `Cursor at: ${selectionStart}<br/>Text before: ${before}<br/>Text after: ${after}`
}
document.getElementById('checkPositionButton').addEventListener('click', checkPosition)