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

I would like to use jQuery to search for a specific character, in this case "#" inside one or more paragraphs, delete that character and wrap everything after the span tag.

Here is an example HTML:

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

And jQuery should convert the code above to this:

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

I have spent several hours on this already, and I know that the solution should be relatively simple, but I can not find it. Is there any jQuery guru who wants to help? Thanks!

+4
source share
4 answers

The following 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); }); 

- If you want to save nested intervals for multiple occurrences: -

Use the working jsFiddle daemon :

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:

  • Several jsFiddle events have been updated to remove the optional var splitText, as this was optional.
  • Several jsFiddle events have been moved, and css has been updated to visually display spaces.
+4
source

Something like that

 $("p:contains('#')").each(function () { var $this = $(this); var thisText = $(this).text().split("#"); $this.html(thisText[0] + "<span>" + thisText[1] + "</span>"; }); 
+2
source

This should work:

 $("p").each(function(){ var text = $(this).text().split("|"); $(this).html(""); var final = text[0] + "<span>" + text[1] + "</span>"; $(this).html(final); }); 
+1
source

Here an example of the following →

 $('p').each(function(i,elem){ var $this = $(this), tStr = $this.text(), res = tStr.replace(/(^.*)(\#.*$)/, '$1<span>$2</span>').replace('#',''); $this.html(res); }); 
+1
source

All Articles