JavaScript code to filter out common words in a string

后端 未结 6 1471
生来不讨喜
生来不讨喜 2020-12-15 12:20

I\'m trying to build JavaScript code that reads one string (say a sentence of English text), then outputs another string of (comma-separated) words that were \"uncommon\". S

6条回答
  •  隐瞒了意图╮
    2020-12-15 13:08

    The String#diff function returns a list of differences (uncommon terms). The terms can be provided as an array or a string.

    You call it like: sentence.diff(terms). Below is a unit test:

    var sentence = 'The dog ran to the other side of the field.';
    var terms    = 'the, it is, we all, a, an, by, to, you, me, he, she, they, we, how, it, i, are, to, for, of';
    // NOTE: The "terms" variable could also be an array.
    
    (sentence.diff(terms).toString() === 'dog,ran,other,side,field')
      ? console.log('pass')
      : console.log('fail');
    

    Below is the 'String.diff' function definition:

    String.prototype.diff = function(terms){
      if (!terms) {
        return [];
      }
    
      if (typeof terms === 'string') {
        terms = terms.split(/,[\s]*/);
      }
    
      if (typeof terms !== 'object' || !Array.isArray(terms)) {
        return [];
      }
    
      terms = terms.map(function(term){
        return term.toLowerCase();
      });
    
      var words = this.split(/[\W]/).filter(function(word){
        return word.length;
      });
    
      return words.filter(function(word){
        return terms.indexOf(word.toLowerCase()) < 0;
      });
    };
    

提交回复
热议问题