search

Home  >  Q&A  >  body text

Find and tag strings in text paragraphs

<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粉253800312P粉253800312486 days ago553

reply all(2)I'll reply

  • P粉670838735

    P粉6708387352023-08-29 15:33:56

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

    reply
    0
  • P粉833546953

    P粉8335469532023-08-29 13:52:37

    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>

    reply
    0
  • Cancelreply