我在不同的元素中有一些文本。我想要的是将特定字符/之间的所有单词包装在 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>
...
最佳答案
使用正则表达式 /\/(.*?)\//g
和 html()
接受回调函数。
正则表达式将匹配斜杠包围的字符串。 (.*?)
会将斜杠内的字符串添加到第一个捕获的组中,该组可在替换部分中使用。
注意:我假设 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/