Find and tag strings in text paragraphs
P粉253800312
P粉253800312 2023-08-28 20:53:07
0
2
517
<p>I have a paragraph, for example: </p> <pre class="brush:html;toolbar:false;"><p> Lorem ipsum <b>amet, consetetur sadipscing elitr, sed diam</b> dolor sit nonumy eirmod tempor Invidunt ut labore et dolore magna aliquyam erat, <i>sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum</i>. Stet clita kasd gubergren, no sea takimata sanctus </p> </pre> <p>There is also a string similar to <code>"Lorem ipsum amet, consetetur sadipscing elitr"</code>. I want to underline this specific string in the original paragraph using Javascript. </p> <p>I think I need to insert a span with a class/ID (-> CSS: text-decoration:underline), but I don't know how to determine the correct index within the paragraph (ignoring any < in a string search ;code><b></code>, <code><i></code>, etc., but including them relative to the span's index). </p> <p>Thanks for any suggestions. </p>
P粉253800312
P粉253800312

reply all(2)
P粉670838735

const text = YourString.replace(/\bMySearch\b/sg, '<u>$1</u>');

P粉833546953

Try this:

//获取元素的内部内容
var text = document.getElementById("text").innerHTML;

//将要替换的文本用<u>标签包围起来
var newtext = text.replace(/Lorem ipsum <b>amet, consetetur sadipscing elitr/g, "<u>Lorem ipsum <b>amet, consetetur sadipscing elitr</u>");

//将新的下划线文本放回元素中
document.getElementById("text").innerHTML = newtext;
<p id="text">
Lorem ipsum <b>amet, consetetur sadipscing elitr, sed diam</b> dolor sit nonumy eirmod  tempor 
invidunt ut labore et dolore magna aliquyam erat, <i>sed diam voluptua. At vero eos et accusam
et justo duo dolores et ea rebum</i>. Stet clita kasd gubergren, no sea takimata sanctus
</p>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template