Home > Net >  Search for string in paragraph and underline it
Search for string in paragraph and underline it

Time:09-22

I have a paragraph, e.g.

<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>

and a string like "Lorem ipsum amet, consetetur sadipscing elitr". I want to achieve underlining this particular string in the original paragraph with Javascript.

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 indices within the paragraph (ignoring any <b>, <i> etc. in the string search but including them wrt the index of the span).

Thanks for any advice.

CodePudding user response:

Try this:

//get the inner contents of the element
var text = document.getElementById("text").innerHTML;

//replace the text you want with that same text surrounded by <u> tags
var newtext = text.replace(/Lorem ipsum <b>amet, consetetur sadipscing elitr/g, "<u>Lorem ipsum <b>amet, consetetur sadipscing elitr</u>");

//put the new underlined text back into the element
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>

CodePudding user response:

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

  • Related