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>

更多相关文章

  1. jQuery返回一个没有逗号的字符串的前5个单词
  2. 如何将每个单词都包含在一个span中,同时保留文本格式
  3. 当将带有撇号的单词保存到数据库时,mysql_real_escape_string会添
  4. 测试一个字符串是否包含PHP中的单词?
  5. 如何在页面上获得带有javascript的特定单词的链接
  6. Python自然语言处理学习笔记(3):1.1 语言计算:文本和单词
  7. 如何在python 3中将单词转换为数字(自己的键和值)?
  8. scikit-learn:在标记化时不要分隔带连字符的单词
  9. [LeetCode] 244. Shortest Word Distance II 最短单词距离 II

随机推荐

  1. 分享三种php生成二维码的方法
  2. 快看!这里有一个PDOStatement::bindParam
  3. PHP+JavaScript实现刷新继续保持倒计时的
  4. 用PHP的FFI调用cjieba
  5. PHP基础案例二:计算学生年龄
  6. PHP结合MySQL实现千万级数据处理
  7. PHP基础案例一:展示学生资料卡
  8. php如何调用phantomJS截图
  9. 教你在PHP ZipArchive解压缩时,去掉zip包
  10. 详解PHP 如何对接 paypal 支付