看看我们的聊天室手动设置的敏感词哈。
那我们前端就首要AJAX请求敏感词H5会话缓存上。比如小编的代码
接下来就好办了,毕竟我们已经把敏感词会话保存到用户的浏览器了,那我们通过JQ获取文章的标题与内容,在自定义个函数进行替换就OK了,比如小编的代码
- //敏感词加载(来源于聊天室)
- $.post('/e/extend/chat/', { enews: "mingganci" }, function(json) {
- sessionStorage.setItem('chatuser_ai_minganci', JSON.stringify(json.minganci));
- }, 'json');
敏感词自定义函数也完成了,最后我们调用这个自定义函数
- function replaceSensitiveWords() {
- let forbiddenWordsStr = sessionStorage.getItem('chatuser_ai_minganci');
- let forbiddenWords = [];
- if (forbiddenWordsStr) {
- forbiddenWords = forbiddenWordsStr.split(',').map(word => word.trim());
- }
- let booknameContent = $('#bookname').text();
- let showContent = $('#content').html();
- let combinedRegex;
- if (forbiddenWords.length > 0) {
- combinedRegex = new RegExp(forbiddenWords.filter(word => word).join('|'), 'ig');
- }
- function replaceInText(text) {
- let hasSensitiveWord = false;
- if (combinedRegex) {
- if (combinedRegex.test(text)) {
- hasSensitiveWord = true;
- text = text.replace(combinedRegex, '***');
- }
- }
- if (hasSensitiveWord) {
- setTimeout(() => {
- layer.msg("有敏感词,已替换", { icon: 5 });
- }, 100);
- }
- return text;
- }
- booknameContent = replaceInText(booknameContent);
- showContent = replaceInText(showContent);
- $(function () {
- $('#bookname').text(booknameContent);
- $('#content').html(showContent);
- });
- }
这样我们就完成了纯js结合文韵坊即时通讯聊天室敏感词把文章内容敏感词变成***。效果截屏
- replaceSensitiveWords();