简体   繁体   中英

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

I've seen a lot of similar questions but I can't seem to figure out exactly how to go about it in my situation. Essentially, I have three different variables: article, arg1, arg2. Article is a string that is about 5 sentences long. Arg1 and arg2 is a sentence/phrase in the article. I'm going to have the article as a basic < p > tag on the website. But I want arg1 and arg2 within the article to be a different color or highlighted or something, so it's obvious where in the article it is. How would I go about searching through the text in the < p > tag, finding each argument, and then changing the style of specific text?

replace with regex is useful:

 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>

shouldn't be hard to achieve by splitting the paragraph into chunks and iterate through occurrences of the variables to add <mark></mark> tag around them.

this can be improved but a simple example would be something like:

 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>

Edit

Emy's solution is more elegant indeed:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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