<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>关键词过滤器</title> </head> <body><h2>关键词过滤器</h2><textarea cols=60 rows=10 id="userInput" placeholder="请输入内容..."></textarea><br> <button onclick="filterKeywords()">提交</button><h3>过滤后的内容:</h3> <textarea cols=60 rows=10 id="filteredOutput" readonly></textarea><h3>关键词(用逗号分隔):</h3> <textarea cols=60 rows=10 id="keywordsInput">http,https,qq,wechat,weixin,.net,.org,.cn,fuck,.com,what app</textarea><script>// 提交时获取关键词并进行过滤function filterKeywords() {const content = document.getElementById("userInput").value;const keywords = getKeywords(); // 获取当前输入的关键词列表 const filteredContent = filterContent(content, keywords);document.getElementById("filteredOutput").value = filteredContent;}// 获取关键词并生成数组function getKeywords() {const input = document.getElementById("keywordsInput").value;return input.split(",").map(keyword => keyword.trim().toLowerCase()).filter(Boolean);}// 过滤内容中的关键词及前10个字符和后30个字符function filterContent(content, keywords) {let result = content;// 构建适用于一般关键词和特殊关键词的正则 const generalKeywords = keywords.filter(k => !k.includes('.')).join("|"); // 一般关键词 const specialKeywords = keywords.filter(k => k.includes('.')).join("|"); // 特殊关键词// 针对一般关键词使用单词边界匹配 const generalRegex = new RegExp(`(${generalKeywords})`, "gi");// 针对特殊关键词,不使用单词边界 const specialRegex = new RegExp(`(${specialKeywords})`, "gi");// 替换一般关键词及其前10个字符和后30字符 result = replaceKeywords(result, generalRegex);// 替换特殊关键词及其前10个字符和后30字符 result = replaceKeywords(result, specialRegex);return result;}// 替换内容中匹配的关键词及其前10个字符和后30个字符function replaceKeywords(content, regex) {let result = content;let match;while ((match = regex.exec(content)) !== null) {const start = match.index;const end = Math.min(content.length, start + match[0].length + 30); // 后30个字符 const startReplace = Math.max(0, start - 10); // 前10个字符 const replaceStr = '*'.repeat(end - startReplace); // 计算总替换长度 result = result.slice(0, startReplace) + replaceStr + result.slice(end);regex.lastIndex = startReplace + replaceStr.length; // 更新正则搜索起点,避免无限循环 }return result;} </script></body> </html>