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!
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With