根据单个单词查找两个字符串之间的差异



我想找出两个字符串之间的区别。到目前为止,我只能返回基于字符的差异:

// Given two strings
let speechA = 'you are and you could';
let speechB = "you are and you couldn't"; 
// I want a logic like difference = speechB - speechA
let difference = speechB.replace(speechA, '');
console.log(difference)

所需的结果应该是:不能

换句话说,我想根据单词而不是字符来找到差异。

我该怎么做?

如果你逐字比较句子,并在同一位置返回句子B与句子A的不同之处,你可以将字符串拆分为单词数组并进行比较:

const speechA = `you are and you could`,
speechB = `you are and you couldn't`
const getStrDifference = (s1, s2) => {
const a1 = s1.split(' '),
a2 = s2.split(' ')
return a2.reduce((diff, word, pos) => (word != a1[pos] && diff.push(word), diff), [])
}
console.log(getStrDifference(speechA, speechB))

只需使用withspace分割字符串并创建数组。然后比较数组。看看以下内容:

// Given two strings
let speechA = 'you are and you could';
let speechB = "you are and you couldn't"; 
// I want a logic like difference = speechB - speechA
let difference =diffOfArrays(speechB.split(' '), speechA.split(' '));
function diffOfArrays(A, B) {
return A.filter(function (a) {
return B.indexOf(a) == -1;
});
}
console.log(difference)

此示例返回位于string1而非string2中的单词数组

const string1 = "hello i am dave gibbs friend";
const string2 = "hello i am mike gibbs buddy";
const string1Arr = string1.split(" ");
const string2Arr = string2.split(" ");
const diffWords = string1Arr.filter( word => {
return !string2Arr.includes(word);
})
console.log(diffWords);

您可以尝试以下方法:

// Given two strings
let speechA = 'you are and you could';
let speechB = "you are and you couldn't"; 
// I want a logic like difference = speechB - speechA
var temp = speechA.split(' ');
let difference = speechB.split(' ').filter(w => !temp.includes(w)).join(', ');
console.log(difference)

最新更新