Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery to select all text inside paragraph after specific character

I would like to use jQuery to find specific character, in this case "#" inside one or more paragraphs, remove that character, and wrap everything after in span tag.

Here is HTML example:

<p>Lorem ipsum dolor sit amet # consectetur adipiscing elit<p>

And jQuery should convert code above into this:

<p>Lorem ipsum dolor sit amet <span>consectetur adipiscing elit</span></p>

I spent few hours on this already and I know solution should be relatively simple, but I can't find it. Is there any jQuery guru willing to help? Thanks!

like image 963
Klikerko Avatar asked Feb 25 '23 11:02

Klikerko


1 Answers

Here is a working jsFiddle demo:

HTML:

<p>Lorem ipsum dolor sit amet # consectetur adipiscing elit</p>

jQuery:

$("p:contains('#')").each(function() {

   var $this = $(this),
       splitText = $this.text().split("#"),
       formattedText = splitText[0] + "<span>" + splitText[1] + "</span>";

   $this.html(formattedText);

});

-- In case you wanted to keep nesting spans for multiple occurrences: --

Use this working jsFiddle demo:

HTML:

<p>Lorem ip#sum dolor sit amet # consectetur adip#iscing elit</p>

jQuery:

$("p:contains('#')").each(function() {

   var $this = $(this),
       thisText = $this.text(),
       numberOfOccurrences = thisText.split("#").length,
       formattedText = thisText.replace(/\#/g, "<span>");

    for (var i = 1; i < numberOfOccurrences; i++) { formattedText += "</span>"; }

    $this.html(formattedText);

});

Update Notes:

  • Multiple Occurrence jsFiddle was updated to remove the extra var splitText, as it was unnecessary.
  • Multiple Occurrence jsFiddle was moved and css was updated to visually show the spans.
like image 112
Code Maverick Avatar answered May 20 '23 03:05

Code Maverick