Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect word before ":" and wrap in "span" using jquery?

I'm trying to detect a character in a text, and if found wrap the word before it in a HTML element, and remove that character.

Example:

Case:

becomes

<span class="th">Case</span>

Method

I can detect the presence of : using:

if (str.indexOf(':') > -1)

To get the word before I'm using:

var th = str.split(':')[0];

To wrap the word in an element I tried:

var th_wrap = "<span class='th'></span>";  
$(th).wrap(th_wrap);

Which doesn't work. To remove the : I tried:

th.replace(':', '');

Which also doesn't work.

To make it slightly more complicated, I want to catch any occurance of someword:, not just the first one.

I'd appreciate any pointers, cheers. (javascript or jQuery)

SNIPPET

var str = $('.target').html();
if (str.indexOf(':') > -1) {
  var th = str.split(':')[0];
  th.replace(':', '');
  var th_wrap = "<span class='th'></span>";
  $(th).wrap(th_wrap);
}
th { font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="target">
  Case 1:
  <br />some text
  <br />some more text
  <br />even more text
  <br />
  <br />Case 2:
  <br />some text
  <br />some more text
  <br />even more text
</p>
like image 819
sol Avatar asked Mar 10 '23 01:03

sol


1 Answers

In your case the words Case 1: and Case 2: are text nodes.

So, you need to get all nodes under target: for this, use jQuery.contents().

The snippet:

$('.target').contents().each(function(idx, ele) {
  if (ele.nodeType == Node.TEXT_NODE &&
            ele.textContent.indexOf(':') > -1) {
    ele.textContent = ele.textContent.replace(':', '');
    $(ele).wrap($('<span/>', {
      class: 'th'
    }));

  }
});
.th {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p class="target">
    Case 1:
    <br />some text
    <br />some more text
    <br />even more text
    <br />
    <br />Case 2:
    <br />some text
    <br />some more text
    <br />even more text
</p>
like image 157
gaetanoM Avatar answered Mar 13 '23 00:03

gaetanoM