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

173
Visualizações
Resalte el contenido de texto o el texto interno de un elemento que contiene otros elementos que también se basan en las palabras buscadas del usuario usando Javascript puro

Cómo resaltar todas las palabras que el usuario está buscando sin afectar el texto de la pantalla y los atributos dentro de los elementos. He intentado algunos enfoques, pero hay un problema como se describe a continuación. Por favor ayuda. Gracias. Manténgase seguro y saludable.

 <input type='text' id='search' onkeyup="highlight(this.value)"> <p id='WE1'><b>WE</b>wE & they<a href="url_With_WE_we_wE_WeOnly">them and We</a><span id="we2">we only.</span></p> function highlight(searchedWords) { var p = document.getElementById("WE1"); var words = searchedWords.trim().split(" "); for (var i=0; i < words.length; i++) { var word = words[i].trim(); /* searchedWords = "We Only"; trial#1: use replaceAll p.innerHTML = p.innerHTML.replaceAll(word, "<mark>" + word + "</mark>"); Issues: 1) replaceAll does not work in other browsers 2) It highlights also the tag attributes containing the searchedWords 3) It is case sensitive, it only highlights the exact match, though I've addressed this using this: var str = p.innerHTML; for (var j=0; j < words.length; j++) { var x = words[j].trim(), string = str.toLowerCase(); while (string.lastIndexOf(x) > -1) { str = str.substring(0, string.lastIndexOf(x)) + "<mark>" + str.substr(string.lastIndexOf(x), words[j].length) + "</mark>" + str.substring(string.lastIndexOf(x) + words[j].length, str.length); string = string.substring(0, string.lastIndexOf(x)); } } p.innerHTML = str; 4) Changing .toLowerCase() also changes the display to lower case var x = p.innerHTML.toLowerCase, word = word.toLowerCase; p.innerHTML = x.replaceAll(word, "<mark>" + word + "</mark>"); trial#2: p.innerHTML = p.innerHTML.replace(new RegExp(words[i], "gi"), (match) => `<mark>${match}</mark>`); Issues: 1) OK, it is NOT case sensitive, it highlights all the searchedWords and the display is OK 2) But, it highlights also the tag attributes containing the searchedWord, anchor tags are affected I tried also using p.childNodes, nodeValue, textContent so that the attributes containing the searchedWord are not affected yet it only inserts the words <mark>SearchedWord</mark> and the searchedWord is not highlighted. */ } }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

replaceAll es una nueva característica es2021. A día de hoy es incompatible con IE.

Te encontré algo que podría funcionar. Eche un vistazo y dígame si todavía tiene problemas Cómo reemplazar todas las apariciones de una cadena en JavaScript en stackoverflow

about 4 years ago · Juan Pablo Isaza Relatório

0

Hice una solución leyendo el HTML interno de derecha a izquierda y descartando la coincidencia si hay un carácter "<" a la izquierda, lo que significa que la coincidencia está dentro de una etiqueta. Aunque la solución a continuación parece ser manual, funciona para mí por ahora.

 <!DOCTYPE html> <html> <input type="text" onkeyup="highlight(this.value)"> <p>Hi! I'm feeling well and happy, hope you too. Thank you.</p> <p id="WE1"><b>WE</b> wE, We, we. <a href="url_With_WE_we_wE_WeOnly">Only you.</a> <span id="wemark">mark it in your calendar.</span> </p> <script> function highlight(searchedWords) { var p = document.getElementsByTagName('p'); for (var i=0; i<p.length; i++) { p[i].innerHTML = p[i].innerHTML.replace(new RegExp("<mark>", "gi"),(match) => ``); p[i].innerHTML = p[i].innerHTML.replace(new RegExp("</mark>","gi"),(match) => ``); } var words = searchedWords.trim(); while (words.indexOf(" ") > -1) {words = words.replace(" "," ")} if (!words) return; words = words.split(" "); for (var i = 0; i < p.length; i++) { p[i].innerHTML = mark(p[i].innerHTML, words) } } function mark(str, words) { try { for (var j=0; j < words.length; j++) { var s = str.toLowerCase(), x = words[j].toLowerCase().trim(); while (s.lastIndexOf(x) > -1) { var loc = s.lastIndexOf(x), y = loc; while (y > 0) { y = y - 1; if (s.substr(y,1)=="<"||s.substr(y,1)==">") break; } if (s.substr(y, 1) != "<") { str = str.substring(0, loc) + "<mark>" + str.substr(loc, x.length) + "</mark>" + str.substring(loc + x.length, str.length); } s = s.substring(0, loc-1); } } return str; } catch(e) {alert(e.message)} } </script> </html>
about 4 years ago · Juan Pablo Isaza 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