Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda