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
source
share