Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
how to get the nearest '<' from cursor position in textarea either js or jquery

Know these but want something like

<script>
    let value = document.getElementById("textarea");
    value.indexOf("<")
    value.lastIndexOf("<")
    value.nearestIndexOf("<") // how can i do it?
</script>
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!