如何检测“:”之前的单词并使用jquery进行“span”包装?
16lz
2021-01-22
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.
我正在尝试检测一个文本中的字符,如果发现在它之前将单词封装在一个HTML元素中,并删除该字符。
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)
我很感激你的指点,干杯。(javascript或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>
更多相关文章
- jQuery返回一个没有逗号的字符串的前5个单词
- 如何将每个单词都包含在一个span中,同时保留文本格式
- 当将带有撇号的单词保存到数据库时,mysql_real_escape_string会添
- 测试一个字符串是否包含PHP中的单词?
- 如何在页面上获得带有javascript的特定单词的链接
- Python自然语言处理学习笔记(3):1.1 语言计算:文本和单词
- 如何在python 3中将单词转换为数字(自己的键和值)?
- scikit-learn:在标记化时不要分隔带连字符的单词
- [LeetCode] 244. Shortest Word Distance II 最短单词距离 II