jQuery regex not showing updates
I have a jQuery snippet I created and am having some issues with displaying the results dynamically. There is an image within each H2 tag. Below is my script of what I'm trying to accomplish:
<h2 id="test">This is a test <img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" width="31" height="16" /></h2>
and my jQuery:
$('h2 img').each(function(){
var = test $(this).html();
$(this).html(test.replace(/<h2>(.*?)\s<img[^>]+src="([^">]+)(.*)\/><\/h2>/gi, '<h2>$1<img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" width="31" height="16" /></h2>'));
]);
It's supposed to move the image next to the word test (removes the extra space between the word test and img tag based on my regex).
Output is supposed to look like below (note: image tag is next to the word test):
<h2 id="test">This is a test<img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" width="31" height="16" /></h2>
I'm trying to accomplish this dynamically. Any help is appreciated.
If your goal is to remove the space after the word 'test' then you can amend the text node directly instead of hacking the HTML around as a string:
let nodes = $('h2').contents().filter((i, node) => node.nodeType === 3);
Array.from(nodes).forEach(n => n.nodeValue = n.nodeValue.trim());
h2 img {
width: 31px;
height: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h2>This is a test <img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" /></h2>
<h2>This is another test <img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" /></h2>
<h2>foo bar <img class="test" src="https://www.iconsdb.com/icons/preview/red/new-xxl.png" alt="test" /></h2>
Better still, fix the problem at the source and don't rely on JS as a crutch to fix issues in your markup.
-- Update --
one last thing can this be converted to a regular function instead of the arrow functions? –
let nodes = $('h2').contents().filter(function(i, node) {
return node.nodeType === 3;
});
Array.from(nodes).forEach(function(n) {
return n.nodeValue = n.nodeValue.trim();
});