Skip to content
Advertisement

How to find strings between square brackets and wrap them in a CSS class

I have the following paragraph:

deemed to be safe and effective for fat reduction by about 20% at certain body sites. As a medical procedure, cryolipolysis is a nonsurgical alternative to liposuction.

How can I find all strings in a [ ] and wrap them in a preferred class?

.hidden{
   display:none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="post-paragraph">The degree of exposure to cooling causes cell death of subcutaneous fat tissue, without apparent damage to the overlying skin.The method has a low rate of complications, and is deemed to be safe and effective for fat reduction by about 20% at certain body sites. As a medical procedure, cryolipolysis is a nonsurgical alternative to liposuction.   </p>

<p class="post-paragraph">The degree of exposure to cooling causes cell death of subcutaneous fat tissue, without apparent damage to the overlying skin.The method has a low rate of complications, and is deemed to be safe and effective for fat reduction by about 20% at certain body sites. As a medical procedure, cryolipolysis is a nonsurgical alternative to liposuction.   </p>

Advertisement

Answer

You can find text and wrap that contain with div class hidden like below.

$('p').each(function(index, element) {
  var str = $('.post-paragraph').text();
  var start = str.indexOf('[');
  var end = str.indexOf(']', start) + 1;
  var text = str.substring(start, end)
  $("p:contains(" + text + ")").html(function(_, html) {
    return html.split(text).join("<div class='hidden'></div>");
  });
});
.hidden {
  display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="post-paragraph">The degree of exposure to cooling causes cell death of subcutaneous fat tissue, without apparent damage to the overlying skin.The method has a low rate of complications, and is deemed to be safe and effective for fat reduction by about 20% at certain
  body sites. As a medical procedure, cryolipolysis is a nonsurgical alternative to liposuction. </p>

<p class="post-paragraph">The degree of exposure to cooling causes cell death of subcutaneous fat tissue, without apparent damage to the overlying skin.The method has a low rate of complications, and is deemed to be safe and effective for fat reduction by about 20% at certain
  body sites. As a medical procedure, cryolipolysis is a nonsurgical alternative to liposuction. </p>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement