Know these but want something like
<script>
let value = document.getElementById("textarea");
value.indexOf("<")
value.lastIndexOf("<")
value.nearestIndexOf("<") // how can i do it?
</script>
You didn't specify what should be selected when the distances are equal to the both directions, here's a snippet, which selects the nearest index from the left-side of the caret.
const textArea = document.querySelector('textarea');
function nearestOf(char, textArea) {
const text = textArea.value,
origo = textArea.selectionStart,
leftIndex = text.lastIndexOf(char, origo - 1),
rightIndex = text.indexOf(char, origo);
let distLeft, distRight, indices = {
[distLeft = leftIndex < 0 ? Infinity : origo - leftIndex]: leftIndex,
[distRight = rightIndex < 0 ? Infinity : rightIndex - origo + 2]: rightIndex
};
return indices[Math.min(distRight, distLeft)];
}
textArea.addEventListener('input', e => {
const s = nearestOf('<', e.target);
console.log('nearestOf:', s);
});
<textarea></textarea>
The code save the nearest < characters from the left-side and right-side of the caret to the Index variables, the distances are stored in dist variables, and in the keys of indices object. If the character is not found from the left-side, the corresponding key is set to Infinity and the value to -1. The same check is done for the right-side character. If there's no the searched character, indices object contains only a single Infinity key. The return statement picks the index of the shortest value from the indices object by the keys which are representing the distances.
The odd looking constant 2 in distRight makes sure, that the left-side is selected when the distances are the same.