【问题标题】:Compare strings in Javascript比较 Javascript 中的字符串
【发布时间】:2017-04-17 11:57:37
【问题描述】:

我需要比较标题(由许多单词组成) 带有一个坏词列表。一句话,indexOf 工作正常。 但是当有很多脏话时就没有了。

有人可以帮忙吗?

var title = "This is my title";
var badwordlist = title.indexOf('fword and other bad words list');
//var badwordlist = title.indexOf('fword');

if ( badwordlist >= 0){
//do something 
}

【问题讨论】:

标签: javascript string compare


【解决方案1】:

我觉得到目前为止发布的两个答案是过度的事情

var title = "fword This is a f**king title.",
  words = title.split(" "),
  badwords = ["fword", "f**king"];

// one of these should do it    

var isGood = words.filter(function(a) {
  return badwords.indexOf(a) == -1;
});

var isBad = words.filter(function(a) {
  return badwords.indexOf(a) != -1;
});

console.log(isBad, isGood);

// if isBad.length>0 then there were swear words in the title

【讨论】:

  • 谢谢!但我需要的是不要过滤掉坏话。我唯一需要的是检测坏词并返回真或假。我该怎么做?
  • return isBad.length>0
  • 你是个天才!谢谢:)
【解决方案2】:

您可以使用String.prototype.includes()来检查字符串是否包含坏词:

var title = "fword This is title.";
var badwords = ["fword", "f**k"];

var isbad = badwords.map(function(a) {
  return title.includes(a);
});

console.log(isbad);

【讨论】:

  • 哦!谢谢@mplungjan 是的 string.includes 也可以。
  • Jai,这是最接近我想要的东西。我需要一个真假。但是为什么 isbad 总是返回 false?
【解决方案3】:

这是一个简单的解决方案,它涉及一个数组、一个循环和一个协调它们的函数

var badwords = ['fword', 'uglyword'];
var replacements = ['*word', 'ug***ord'];
function replaceBadwords(title) {
    for (var badwordIndex in badwords) {
        if (title.indexOf(badwords[badwordIndex]) >= 0) {
            title = title.split(badwords[badwordIndex]).join(replacements[badwordIndex]);
        }
    }
}

然而,“assignment”这个词包含了一个丑陋的词,其实并不丑陋。我的意思是,如果您只阅读前三个字符,您会认为这是一个丑陋的词。为了应对这些例外情况,请确保您也不会审查这些例外情况。

【讨论】:

    【解决方案4】:

    this SO question。这样就可以了:

    var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
    
    function checker(value) {
      var prohibited = ['banana', 'apple'];
    
      for (var i = 0; i < prohibited.length; i++) {
        if (value.indexOf(prohibited[i]) > -1) {
          return false;
        }
      }
      return true;
    }
    
    arr = arr.filter(checker);
    console.log(arr);

    通过在空格上拆分标题来获得 arr,例如 title.split(" ")

    完成任何过滤后,您可以使用title = arr.join(" ") 创建过滤标题。

    【讨论】:

    • 感谢您的回复。问题是我的标题每次都不一样。如何将其存储在数组中? var title = "这是我的头衔"; var title = tab.title;
    • 您是否阅读了完整的答案?最后它说通过在空间上拆分标题来获取 arr,例如 title.split(" ")
    • 我认为你不明白字符串本身就是数组,可以使用indexOf进行检查
    • 为什么要使用循环函数进行过滤?这似乎有点矫枉过正
    • 看看我的回答是什么意思
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2014-12-02
    • 2018-06-14
    • 1970-01-01
    • 2017-06-27
    相关资源
    最近更新 更多