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

I am trying to detect a character in the text, and if it is found, wrap the word in front of it in the HTML element and delete that character.

Example:

Case:

becomes

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

Method

I can detect the presence :using:

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

To get the word before I use:

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

To wrap a word in an element I tried:

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

What does not work. To remove :, I tried:

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

Which doesn't work either.

To make this a little harder, I want to catch any mistake someword:, not just the first one.

I would appreciate any pointers, greetings. (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>
Run code
+4
source share
2

1: 2: .

, target: jQuery.contents().

:

$('.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>
+5

regex . jquery .html(function), html p. String.prototype.replace(), .

$("p").html(function(i, html){
  return html.replace(/(\w+\s\d+):/g, "<span class='th'>$1</span>");
});
.th { color: red }
<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>
+2

Source: https://habr.com/ru/post/1668030/


All Articles