JavaScript code to filter out common words in a string

后端 未结 6 1478
生来不讨喜
生来不讨喜 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:11

    Here you go:

    function getUncommon(sentence, common) {
        var wordArr = sentence.match(/\w+/g),
            commonObj = {},
            uncommonArr = [],
            word, i;
    
        common = common.split(',');
        for ( i = 0; i < common.length; i++ ) {
            commonObj[ common[i].trim() ] = true;
        }
    
        for ( i = 0; i < wordArr.length; i++ ) {
            word = wordArr[i].trim().toLowerCase();
            if ( !commonObj[word] ) {
                uncommonArr.push(word);
            }
        }
    
        return uncommonArr;
    }
    

    Live demo: http://jsfiddle.net/simevidas/knXkS/

提交回复
热议问题