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>