Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda