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
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;
});
};