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.
source share