Find and tag strings in text paragraphs
P粉253800312
2023-08-28 20:53:07
<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>
const text = YourString.replace(/\bMySearch\b/sg, '<u>$1</u>');
Try this: