向字符串比较代码中添加遗漏的单词?

时间:2019-05-24 12:50:40

标签: javascript

这是将 str1 (参考)与 str2 (用户输入)进行比较的代码。

    // str1 is the reference text. 
    var str1 = "I was sent to earth to protect my cousin";

    // str2 is the text which I want to compare with str1.
    var str2 = "I was send to earth to protect my sister"

    function words(s) {
        return s.toLowerCase().match(/\w+/g);
    }

    let a = words(str1);
    let b = words(str2);
    let res1 = b.filter(i => !a.includes(i));
    let res2 = a.filter(i => !b.includes(i));

    highlight(b, "str2", res1);
    function highlight(str, id, res){
        var text = "";
       for(var i=0; i<str.length; i++){
        var hasVal = res.includes(str[i]);
        if(hasVal){
          text +=" <span style='color:red'>"+str[i]+"</span> ";
        } else {
           text +=" "+str[i]+" ";
        }
       }
        document.write(text);
    }

这是上面代码的输出:

(参考字符串为:var str1 = "I was sent to earth to protect my cousin"

enter image description here

如您所见,它只是比较两个字符串( str1 str2 )并将差异的颜色更改为红色。

现在的问题是,如果我只是从 str2 中删除“ 已发送”一词,就会得到以下输出:

enter image description here

相反,我想将缺少的单词添加到带有橙色的输出中,如下所示:

enter image description here

也是一个技术问题...我如何确定这是一个遗漏的单词,而不是另一个拼写错误的单词?!

0 个答案:

没有答案