MoHamed HaSsn MoHamed HaSsn - 4 years ago 148
CSS Question

wrap text in span element

I Tried To Wrap Some Text In Span Depend On Data-Text.
For Example If I Have This Code:

<div data-text="world">Hello World We Love JavaScript</div>


I'd Like To Wrap It Like This:

<div data-text="world">Hello <span>World</span> We Love JavaScript</div>


I have tried to solve this problem Using JQuery Replace() Method But I have not yet found the right solution:



$("div").text(function (index, text) {
return text.replace($("div").data("text"), "<span>" + $("div").data("text") + "</span>");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-text="Hello">Hello <span>World</span> We Love JavaScript</div>




Answer Source

Use html() method with a callback and generate regex using the attribute value with word boundary(to match only the exact word) to replace the word with wrapped span.

$('div[data-text]').html(function(_, htm) {
  return htm.replace(new RegExp('\\b' + $(this).data('text') + '\\b', 'ig'), '<span>$&</span>')
})
div span {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-text="Hello|love">Hello World We Love JavaScript</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download