Reputation: 105
I have some code to replace any instance of ##Some Content## in my page content within #body-inner and replace it with:
<span class="tooltipster" data-tooltip-content="#Some Content">Some Content</span>
This is working OK, but would like to convert the data-tooltip-content="#Some Content"
to lowercase and remove the spaces with a "-".
See code below:
$('#body-inner').children().each(function(){
$(this).html(
$(this).html().replace(/##(.*?)##/gm,'<span class="tooltipster" data-tooltip-content="#$1">$1</span>')
);
});
Upvotes: 1
Views: 31
Reputation: 115222
You can do it using replace#String
with a callback function. Although you can avoid each()
method by using a callback with html()
method.
// use html method with callback which iterates over the element where old html is the second argument
$('#body-inner').children().html(function(i, html) {
// replace all match substring
return html.replace(/##(.*?)##/gm, function(m, m1) {
// generate the html string
return '<span class="tooltipster" data-tooltip-content="#' + m1.toLowerCase().split(' ').join('-') + '">' + m1 + '</span>';
// instead of split and join, you can also use .replace(/\s/g, '-')
});
});
$('#body-inner').children().html(function(i, html) {
return html.replace(/##(.*?)##/gm, function(m, m1) {
return '<span class="tooltipster" data-tooltip-content="#' + m1.toLowerCase().split(' ').join('-') + '">' + m1 + '</span>';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body-inner">
<div>##abc def##</div>
<div>abc ##def dfdfd## ##fdfdf sdsds##</div>
</div>
Upvotes: 2