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's 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>
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>
You need to set html of element instead of text :
$("div").html(function(i,html) {
return html.replace(/(World)/g, '<span>World</span>');
});
$("div").html(function(i,html) {
return html.replace(/(World)/g, '<span>World</span>');
});
<style>span{color:red}</style>
<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>
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