包裹特定字符之间的所有单词

时间:2017-04-21 11:06:18

标签: jquery regex string

我有一些不同元素的文字。我想要的是在span元素中的特定字符/之间包装所有单词。见下面的例子。

<ul>
<li>/Lorem Ipsum/ has been the industry's standard.</li>
<li>With desktop publishing software like Aldus PageMaker including versions of /Lorem Ipsum../</li>
<li>There are /many/ variations of passages of /Lorem/ Ipsum available, but the..</li>
</ul>

我想知道这可能。因为据我所知,每个元素只能占一个字。例如,此元素在/.

之间有两个单词
<li>There are /many/ variations of passages of /Lorem/ Ipsum available, but the..</li>

应该是

<ul>
<li><span class="wrapped">Lorem Ipsum</span> has been the industry's standard.</li>
...

1 个答案:

答案 0 :(得分:3)

使用正则表达式/\/(.*?)\//ghtml()接受回调函数。

正则表达式将匹配斜杠包围的字符串。 (.*?)会将字符串内部的斜杠添加到第一个捕获的组中,该组可用于替换部分。

注意:我认为li内没有嵌套的HTML元素。

$('ul li').html(function(i, html) {
  return html.replace(/\/(.*?)\//g, '<span class="highlighted">$1</span>');
});
span.highlighted {
  font-weight: bold;
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>/Lorem Ipsum/ has been the industry's standard.</li>
  <li>With desktop publishing software like Aldus PageMaker including versions of /Lorem Ipsum../</li>
  <li>There are /many/ variations of passages of /Lorem/ Ipsum available, but the..</li>
</ul>

相关问题