jQuery 在元素中查找一串文本并在其周围包裹一些 span 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16090487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find a string of text in an element and wrap some span tags round it
提问by Seb
I want to find a string of text in an element and wrap some span tags round it. E.g.
我想在一个元素中找到一串文本并在它周围包裹一些 span 标签。例如
From:
从:
<h2>We have cows on our farm</h2>
To:
到:
<h2>We have <span class='smallcaps'>cows</span> on our farm</h2>
I've tried:
我试过了:
$("h2:contains('cow')").each(function() {
$(this).text().wrap("<span class='smallcaps'></span>");
});
But that only wraps the whole containing h2
tag.
但这只会包装整个包含h2
标签。
回答by undefined
$("h2:contains('cow')").html(function(_, html) {
return html.replace(/(cow)/g, '<span class="smallcaps"></span>');
});
回答by Justin Bicknell
Another approach, split by keyword and join with the updated html.
另一种方法,按关键字拆分并加入更新的 html。
$("h2:contains('cow')").html(function(_, html) {
return html.split('cow').join("<span class='smallcaps'>cow</span>");
});
Note: I haven't tested this, but I'm assuming this would perform worse than doing a replace, but figure I would include anyways for informative purposes
注意:我还没有测试过这个,但我假设这会比做替换更糟糕,但我还是会为了提供信息而包括在内
回答by Justin Haight
Here is a variation on @undefined's answer, which loops through an array of items:
这是@undefined's answer的一个变体,它循环遍历一组项目:
var barnyardArray = [
'cow',
'horse',
'chicken',
'hog',
'goat',
'goose',
'duck',
'llama'
];
$.each(barnyardArray, function (index, value) {
$("p:contains(" + value + ")").html(function (_, html) {
var regex = new RegExp(value, 'g');
return html.replace(regex, '<span class="smallcaps">' + value + '</span>');
});
});
回答by Wiktor Stribi?ew
You usually want to match some arbitrary text in a case insensitive way. Sometimes, search queries contain characters that are special regex metacharacters and must be escaped before compiling the pattern.
您通常希望以不区分大小写的方式匹配一些任意文本。有时,搜索查询包含特殊正则表达式元字符的字符,必须在编译模式之前进行转义。
Use a solution like
使用类似的解决方案
var words = ["cows", "c++", "$var$"];
$("h2").html(function(_, html) {
return html.replace(new RegExp(words.map(function(x) {
return x.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&')
}).join('|'), "gi"), '<span class="smallcaps">$&</span>')
});
span { color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>We have cows on our farm</h2>
<h2>C++ Apps $var$</h2>
Note that here, a regex will look like /cows|c\+\+|\$var\$/gi
, where +
and $
, special regex metacharacters, are escaped, and the alternatives are ORed with the |
alternation operator.
请注意,在这里,一个正则表达式的样子/cows|c\+\+|\$var\$/gi
,在那里+
和$
,特殊的正则表达式元字符,都逃出来了,替代与逻辑或|
交替操作。
Also, note that there is no need of any outer parentheses as the default group is Group 0 that holds the whole match, and the backreference to Group 0 in JavaScript regex is $&
. Thus, the replacement is always done with the search word in the exact case as it was found in text.
另请注意,不需要任何外括号,因为默认组是包含整个匹配项的组 0,并且 JavaScript 正则表达式中对组 0 的反向引用是$&
. 因此,替换总是在与在文本中找到的完全相同的情况下使用搜索词完成。
Note that in case you need to match whole words only, you would need special boundaries, either \b
(if the search words always consist of letters, digits or _
) or (\W|^)
/ (?!\w)
(if there can be special characters):
请注意,如果您只需要匹配整个单词,则需要特殊的边界\b
(如果搜索词始终由字母、数字或 组成_
)或(\W|^)
/ (?!\w)
(如果可以有特殊字符):
var words = ["cows", "c++", "$var$"];
$("h2").html(function(_, html) {
return html.replace(new RegExp("(\W|^)(" + words.map(function(x) {
return x.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&')
}).join('|') + ")(?!\w)", "gi"), '<span class="smallcaps"></span>')
});
span { color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>We have cows in our farm cowshed</h2>
<h2>C++ Apps $var$ in $var$moretext</h2>
回答by Shraftali
In my case i have some tag inside the target div and some text i need to wrap that text into a link.
在我的情况下,我在目标 div 中有一些标签和一些文本,我需要将该文本包装到链接中。
This how i did following "What have you tried".
这就是我在“你尝试过什么”之后所做的。
var oldText = $(this).text(),
newText = $(this).html().replace(
oldText,
"<a class='k-link' href='#' class='smallcaps'>" +
oldText +
"<span class='k-icon k-i-arrow-n'></span></a>"
);
$(this).html(newText);
回答by What have you tried
$("h2:contains('cow')").each(function() {
var newText = $(this).html().replace("cow", "<span class='smallcaps'></span>");
$(this).html(newText);
});