0

I've got something like this:

<p id="tire">I need new tires for my car</p>

I'm trying to write something that would highlight word(s) that I assign, but NOT the stuff that is considered a tag. For example, if I want to highlight "tire", I'd theoretically see:

<p id="tire">I need new <strong>tire</strong>s for my car</p>

But unfortunately, I see:

<p id="<strong>tire</strong>">I need new <strong>tire</strong>s for my car</p>

I'm using just a simple replaceAll(oldWord, newFormat). Is there a library that can help? I am using jsoup to grab the HTML I would be searching through.

4

3 回答 3

3

您可以使用选择方法getElementsContainingOwnText(String searchText)来选择包含您要查找的单词的元素。在这种情况下,“轮胎”。

例如它是如何工作的:

虚拟 HTML

<html>
 <head></head>
 <body> 
  <p id="tire">I need new tires for my car</p>
 </body>
</html>

我们的 Jsoup 代码:

Elements e = doc.getElementsContainingOwnText("tire");
for (Element el : e) {
    el.text(el.ownText().replace("tire", "<strong>tire</strong>"));
}

生成的文档打印输出:

<html>
 <head></head>
 <body> 
  <p id="tire">I need new <strong>tire</strong>s for my car</p>
 </body>
</html>
于 2013-10-10T21:16:11.260 回答
0

使用查找和替换,在单词前面添加一个空格,例如“轮胎”

并替换<strong>tire</strong>s

于 2013-10-10T19:20:43.523 回答
0

尝试:

replaceAll("tire", "<strong>tire</strong>");
replaceAll("id=\"<strong>tire</strong>\"", "id=\"tire\"");

这解决了特定问题,但你可以得到其他我认为

于 2013-10-10T19:23:54.043 回答