JavaScript检测文章敏感词

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

 1 //将文章中匹配到的敏感词罗列出来
 2 <span style="color:#CC6600">敏感词:</span><font color='red' id="show_word"></font>   
 3 
 4 //文章显示区域
 5 <div style="overflow-x:hidden;scrollbar-arrow-color:yellow;scrollbar-base-color:lightsalmon;background: #EAF3FA;" id="dispose_content"></div>
 6 //1.在视图模板(本示例中使用的是laravel中的blade模板)中使用js接受文章正文内容,先暂存起来
 7 var contents = "{!! $data['article_content'] !!}";  //文章内容先存在变量contents中
 8 
 9 //2.再使用ajax去获取敏感词,并使用正则在文章循环匹配每一个敏感词
10 $.ajax({
11     url: "{{Config::get('app.blog_cms')}}article/sensitiveword", //请求该方法获得铭感词
12     type: 'get',
13     dataType: 'json',
14 }).done(function(data) {
15     if(data.code == 200){
16         var str = '';
17         $.each(data.data, function(i, e) {
18             if(contents.indexOf(e.word) > 0){
19                 str += e.word+', ';
20                 //若匹配到了铭感词使用高亮显示,这里使用的是红色显示
21                 contents = contents.replace(new RegExp(e.word,"gm"), '<span style="color:red;">'+e.word+'</span>');
22             }
23         });
24         $('#show_word').html(str);   //将匹配到的敏感词放到敏感词显示区域
25         $('#dispose_content').html(contents);    //将敏感词高亮后的文章放到文章显示区域
26     }
27 }).fail(function() {
28     console.log("error");
29 });
原文地址:https://www.cnblogs.com/iaknehc/p/6218772.html