I am using the following jQuery snippet to wrap a span around a specified piece of text:
我使用以下jQuery代码段来围绕指定的文本片段包装:
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/(cow)/g, '<span class="smallcaps">$1</span>')
});
In this instance, the word 'cow' is the target. However, I only want the word 'cow' to be highlighted, not words that contain 'cow' such as 'cows' or 'cowbodys'.
在这种情况下,“牛”这个词就是目标。但是,我只想要突出显示“牛”这个词,而不是包含“牛”的词,例如“奶牛”或“牛群”。
How can I do this?
我怎样才能做到这一点?
在这里小提琴
2 个解决方案
#1
2
Just change it to
只需将其更改为
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/\b(cow)\b/g, '<span class="smallcaps">$1</span>')
});
\b
in a regular expression is a word boundary. See MDN.
正则表达式中的\ b是单词边界。见MDN。
#2
2
Simply put: \b
as it allows you to perform a "whole word only
" search using a regular expression
简单地说:\ b因为它允许您使用正则表达式执行“仅限全字”搜索
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/\b(cow)\b/g, '<span class="smallcaps">$1</span>')
});
span { color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>We have cows on cowboy town cow</h2>
#1
2
Just change it to
只需将其更改为
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/\b(cow)\b/g, '<span class="smallcaps">$1</span>')
});
\b
in a regular expression is a word boundary. See MDN.
正则表达式中的\ b是单词边界。见MDN。
#2
2
Simply put: \b
as it allows you to perform a "whole word only
" search using a regular expression
简单地说:\ b因为它允许您使用正则表达式执行“仅限全字”搜索
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/\b(cow)\b/g, '<span class="smallcaps">$1</span>')
});
span { color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>We have cows on cowboy town cow</h2>