js检测文章敏感词

时间:2023-03-10 01:01:49
js检测文章敏感词

在一些博客或者论坛中,文章中的敏感词需要显示出来和高亮显示起到提示用户的作用。这个功能实现的方法有很多,下面是js的实现方式。

 //将文章中匹配到的敏感词罗列出来
<span style="color:#CC6600">敏感词:</span><font color='red' id="show_word"></font> //文章显示区域
<div style="overflow-x:hidden;scrollbar-arrow-color:yellow;scrollbar-base-color:lightsalmon;background: #EAF3FA;" id="dispose_content"></div>
//1.在视图模板(本示例中使用的是laravel中的blade模板)中使用js接受文章正文内容,先暂存起来
var contents = "{!! $data['article_content'] !!}"; //文章内容先存在变量contents中 //2.再使用ajax去获取敏感词,并使用正则在文章循环匹配每一个敏感词
$.ajax({
url: "{{\Config::get('app.blog_cms')}}article/sensitiveword", //请求该方法获得铭感词
type: 'get',
dataType: 'json',
}).done(function(data) {
if(data.code == 200){
var str = '';
$.each(data.data, function(i, e) {
if(contents.indexOf(e.word) > 0){
str += e.word+', ';
//若匹配到了铭感词使用高亮显示,这里使用的是红色显示
contents = contents.replace(new RegExp(e.word,"gm"), '<span style="color:red;">'+e.word+'</span>');
}
});
$('#show_word').html(str); //将匹配到的敏感词放到敏感词显示区域
$('#dispose_content').html(contents); //将敏感词高亮后的文章放到文章显示区域
}
}).fail(function() {
console.log("error");
});