正则替换标签内的字符串

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.dd{
color:aquamarine;
font-size: 20px;
}
</style>
</head>
<body>
<div class="dd">★</div>
<div class="dd">✩</div>

</body>
</html>
<script src="lib/js/jquery-3.1.1.min.js"></script>
<script>
//高亮关键字 text =>内容 words:关键词 tag 被包裹的标签
console.log(highLightKeywords('这是对的吗','这是的啊'));
console.log(highLightKeyw('这是对的吗','这是'));
console.log(highlight('这是对的吗','这是'));
//匹配每一个关键字字符
function highLightKeywords(text, words, tag) {
tag = tag || 'span';// 默认的标签,如果没有指定,使用span
var i, len = words.length, re;
for (i = 0; i < len; i++) {
// 正则匹配所有的文本
re = new RegExp(words[i], 'g');
console.log(re)
if (re.test(text)) {
text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
// text = text.replace(re, '<'+ tag +' class="highlight">'+words[i]+'</'+ tag +'>');
}
}
return text;
}

function highLightKeyw(text, words, tag) {
tag = tag || 'span';// 默认的标签,如果没有指定,使用span
//匹配整个关键词
re = new RegExp(words, 'g');

if(re.test(text)) {
text = text.replace(re, '<' + tag + ' class="highlight">$&</' + tag + '>');
}
return text;
}
 
//匹配整个关键词 不拆分
function highlight(text, words, tag) {
// 默认的标签,如果没有指定,使用span
tag = tag || 'span';
var i, len = words.length,
re;
//匹配每一个特殊字符 ,进行转义
var specialStr = ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\\", "(", ")", "/", "%"];
$.each(specialStr, function(i, item) {
if(words.indexOf(item) != -1) {
words = words.replace(new RegExp("\\" + item, 'g'), "\\" + item);
}
});
re = new RegExp(words, 'g');
if(re.test(text)) {
text = text.replace(re, '<' + tag + ' class="highlight">$&</' + tag + '>');
}
return text;

}

</script>
posted @ 2019-01-22 17:35  IT刘磊  阅读(1180)  评论(0编辑  收藏  举报