Home > Software engineering >  jQuery: Wrap parentheses and its content when a class is found in parentheses
jQuery: Wrap parentheses and its content when a class is found in parentheses

Time:11-05

I need to wrap code between parenthesis() if a specific class is found.

I am using a regex to highlight parenthesis.

var o = jQuery(".wp-site-blocks");
o.html(o.html().replace(/\([^\)]*?\)/g, '<span >$&</span>'));

HTML looks like

(Some Text, 2022, 2021<span ><a href="#">11</a></span><span ><a href="#">12</a></span>)

But cant find a way to check if parenthesis have a specific class(.vbSup) in it then highlight otherwise ignore.

Its a long page with more than one parenthesis.

$o = $(".wp-site-blocks p:has(.vbSup)");
$o.html(function(i, oldhtml) {
  return oldhtml.replace(/\([^\)]*?\)/g, '<span >$&</span>');
});
.highlight{
  background-color:yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div >

  <p>“Tragically, some 80% of the world’s hungry children live in countries with actual food surpluses, much of which is in the form of feed fed to animals which will be consumed by only the well-to-do consumers.”(Jeremy Rifkin, noted author of 23 books
    on the impact of global changes<span ><a href="#3af76716-b152-4705-a76f-f452228b13db" id="3af76716-b152-4705-a76f-f452228b13db-link">21</a></span>)</p>


  <p>“82% of the world’s starving children live in countries where food is fed to animals that are then killed and eaten by more well-off individuals in developed countries like the US, UK, and in Europe.” (Dr. Richard Oppenlander, 2012 Book )<span ><a href="#4bc2d108-83cb-49d4-918a-ea268c84b090" id="4bc2d108-83cb-49d4-918a-ea268c84b090-link">22</a></span></p>
</div>

CodePudding user response:

Use a function as the replacement, so it can check whether the old contents contain vbSup.

$o = $(".wp-site-blocks p");
$o.html((i, oldhtml) =>
  oldhtml.replace(/\([^\)]*?\)/g, (m) =>
    m.includes('vbSup') ? `<span >${m}</span>` : m));
.highlight {
  background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div >

  <p>“Tragically, some 80% of the world’s hungry children live in countries with actual food surpluses, much of which is in the form of feed fed to animals which will be consumed by only the well-to-do consumers.”(Jeremy Rifkin, noted author of 23 books
    on the impact of global changes<span ><a href="#3af76716-b152-4705-a76f-f452228b13db" id="3af76716-b152-4705-a76f-f452228b13db-link">21</a></span>)</p>


  <p>“82% of the world’s starving children live in countries where food is fed to animals that are then killed and eaten by more well-off individuals in developed countries like the US, UK, and in Europe.” (Dr. Richard Oppenlander, 2012 Book )<span ><a href="#4bc2d108-83cb-49d4-918a-ea268c84b090" id="4bc2d108-83cb-49d4-918a-ea268c84b090-link">22</a></span></p>

</div>

  • Related