定义js方法
function buildMap(wordList) {
var result = {};
var count = wordList.length;
for (var i = 0; i < count; ++i) {
var map = result;
var word = wordList[i];
for (var j = 0; j < word.length; ++j) {
var ch = word.charAt(j);
if (typeof(map[ch]) != "undefined") {
map = map[ch];
if (map["empty"]) {
break;
}
}
else {
if (map["empty"]) {
delete map["empty"];
}
map[ch] = {"empty":true};
map = map[ch];
}
}
}
return result;
}
function check(map, content) {
var result = [];
var count = content.length;
var stack = [];
var point = map;
for (var i = 0; i < count; ++i) {
var ch = content.charAt(i);
var item = point[ch];
if (typeof(item) == "undefined") {
i = i - stack.length;
stack = [];
point = map;
}
else if (item["empty"]) {
stack.push(ch);
result.push("****");//转换为*号
stack = [];
point = map;
}
else {
stack.push(ch);
point = item;
}
}
在html中引用
<textarea id="content" class="aui-input" style="border:1px solid red;"> </textarea>
<button type="button" name="button" οnclick="fndd()">查询</button>
<script type="text/javascript">
function fndd() {
var sensitive=["暴力", "色情", "fuck", "TMD"];//敏感词词库
var content=$api.val($api.byId('content'));//获取输入内容
var map = buildMap(sensitive.sort());
var words = check(map, content);
alert(words);
}
</script>