簡體   English   中英

如何在 HTML 的一段文本中搜索一個短語,然后突出顯示/着色?

[英]How would I search for a phrase in a section of text in HTML and then highlight/color it?

我已經看到了很多類似的問題,但我似乎無法弄清楚在我的情況下如何確切地了解它。 本質上,我有三個不同的變量:article、arg1、arg2。 文章是一個大約 5 個句子長的字符串。 Arg1 和 arg2 是文章中的一個句子/短語。 我將把這篇文章作為網站上的基本 < p > 標簽。 但我希望文章中的 arg1 和 arg2 是不同的顏色或突出顯示或其他東西,所以很明顯它在文章中的位置。 我將如何 go 搜索 < p > 標簽中的文本,找到每個參數,然后更改特定文本的樣式?

用正則表達式替換很有用:

 let str = document.getElementById("str"); let result; result = str.innerHTML.replace(/Lorem Ipsum/gi, `<span class="my-span">Lorem Ipsum</span>`).replace(/specimen book/gi, `<span class="my-span">specimen book</span>`); str.innerHTML = result; console.log(str);
 p.my-span { color: red; font-weight: bold }
 <p id="str">Lorem Ipsum is simply dummy text of the printing and specimen book typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, Lorem Ipsum but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,Lorem Ipsum and more recently with desktop specimen book publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>

通過將段落分成塊並遍歷變量的出現以在它們周圍添加<mark></mark>標記,應該不難實現。

這可以改進,但一個簡單的例子是這樣的:

 let arg = "dummy"; let paragraph = document.getElementById('paragraph'); let broken = paragraph.innerHTML.split(arg); paragraph.innerHTML = ''; broken.map((part, i) => { paragraph.innerHTML += i + 1 >= broken.length? part: part + ' <mark>' + arg + '</mark>'; });
 <p id="paragraph">this is just a dummy text and like any other dummy text it does nothing besides being dummy</p>

編輯

Emy 的解決方案確實更優雅:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM