简体   繁体   English

在特定标签内查找单词

[英]Find a word inside specific tags

  let find_word="xyz"
       let el=document.getElementById("text");
        let arr = el.innerHTML.split(" ");
let newarr=[];
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] === find_word) {
            newarr[i] = `<span class="highlight">${arr[i]}</span>`;
          } else {
            newarr[i] = arr[i];
          }
        }
el.innerHTML=newarr.join(" ")

I highlighted the two xyz's in the sentence but I can't highlight the others I need to highlight the xyz's in the li tags but not in the subtag我突出显示了句子中的两个 xyz,但无法突出显示其他我需要突出显示 li 标签中的 xyz,但不突出显示子标签中的 xyz

<div id="text"> Nature, in xyz broadest xyz 
<ul>
<li>xyz</li>
<li>xyz</li>
</ul> 
<sub>xyz</sub> <sub>xyz</sub> sense of world.</div>

Please give me a better example of doing this.请给我一个更好的例子。 I am not good at regex.我不擅长正则表达式。 I just know the basic regex.我只知道基本的正则表达式。 If regex can be a solution for this.如果正则表达式可以解决这个问题。 suggest me some, please.请给我一些建议。

Following your edits in the question, try this:在您对问题进行编辑之后,请尝试以下操作:

el.innerHTML.split(/\b/);

The thing is that "xyz" is not surrounded by spaces in the places you are missing.问题是“xyz”在您缺少的地方没有被空格包围。

\b indicates a word boundary, so it will capture your missing occurences. \b 表示单词边界,因此它将捕获您丢失的事件。

Note that, depending on what you are doing, it might be not completely safe, eg if the li element could have class="xyz" things will likely get messed up.请注意,根据您正在做的事情,它可能并不完全安全,例如,如果 li 元素可能有class="xyz" ,事情可能会变得一团糟。

Hope that helps...希望有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM