我该如何做一个jQuery脏话/坏词过滤器? [英] how can I do a jQuery swear word / bad word filter?

查看:83
本文介绍了我该如何做一个jQuery脏话/坏词过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于为什么这是一个坏主意的争论,但是在我的实现中,我计划在帐户设置中启用/禁用坏词.换句话说,默认情况下,不良词是可见的,但是如果被询问,则将其关闭/隐藏.

计划将向客户端发送JSON字符串,并让客户端过滤掉不良词.

json字符串

['swear1', 'swear2']

原始短语

this phrase includes swear1

最终输出

this phrase includes ****

这是我到目前为止尝试过的

    $(document).ready (function () {
        $('body').html().replace('asdf', 'ffff');
    });

现在要注意的是,我正在使用asp.net mvc,并且可以在服务器端做到"这一点,但是我认为如果卸载到客户端,这样做会更好.对此的建议.

解决方案

类似的方法可能有效:

String.prototype.repeat = function(num){
  return new Array(num + 1).join(this);
}

var filter = ['ass', 'piss'];

$('.post').text(function(i, txt){

  // iterate over all words
  for(var i=0; i<filter.length; i++){

    // Create a regular expression and make it global
    var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');

    // Create a new string filled with '*'
    var replacement = '*'.repeat(filter[i].length);

    txt = txt.replace(pattern, replacement);
  }

  // returning txt will set the new text value for the current element
  return txt;
});

在jsFiddle上运行 示例

编辑:添加了边界,因此不会替换包含脏话的单词.我使用了双反斜杠,因为反斜杠应在字符串中转义,请参阅本主题. /p>

I know there are many arguments as to why this is a bad idea, but in my implementation I'm planning on enabling/disabling bad words in the account settings. In other words, bad words will be visible by default, but switched off / hidden if asked.

The plan will be to send a JSON string to the client and let the client filter out the bad words.

json string

['swear1', 'swear2']

original phrase

this phrase includes swear1

final output

this phrase includes ****

this is what I've tried so far

    $(document).ready (function () {
        $('body').html().replace('asdf', 'ffff');
    });

now on a side note, I am using asp.net mvc and I "could" do this on the server side, but I was thinking that this would be better if offloaded to the client... I'm open to suggestions on this.

解决方案

Something like this might work:

String.prototype.repeat = function(num){
  return new Array(num + 1).join(this);
}

var filter = ['ass', 'piss'];

$('.post').text(function(i, txt){

  // iterate over all words
  for(var i=0; i<filter.length; i++){

    // Create a regular expression and make it global
    var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');

    // Create a new string filled with '*'
    var replacement = '*'.repeat(filter[i].length);

    txt = txt.replace(pattern, replacement);
  }

  // returning txt will set the new text value for the current element
  return txt;
});

Working example on jsFiddle

Edit: Added boundaries so it won't replace words that contain the swear words. I've used double backslashes because backslashes should be escaped in a string, see this topic.

这篇关于我该如何做一个jQuery脏话/坏词过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆