jquery - 将所有单词包裹在特定字符之间

标签 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>
...

最佳答案

使用正则表达式 /\/(.*?)\//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>

关于jquery - 将所有单词包裹在特定字符之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541143/

相关文章:

jquery - Fancybox 停止滚动到中心

python - 有没有办法打印使用 re.compile 创建的模式中的每个项目?

Java:带有管道特殊字符的 split() 方法

java - 将 EditText 中的字符串解析为 double 会导致运行时错误

jquery - 如何按计数 .remove()

javascript - 最佳编码实践 JavaScript

javascript - 正则表达式 - 检测并替换字符串中两个以上的数字

java - 使用 `import java.util.Random` 如何获得不重复的结果?

c# - 如何正确地将 .NET 字符串编码为 native 代码的 std::wstrings?

javascript - 我可以调整浏览器窗口的大小吗?