首页 > 解决方案 > 查找在字符串中添加和删除了哪些单词,包括重复项

问题描述

因此,如果添加的单词之一已经存在于修改后的字符串中,那么我在过滤掉添加和删除到字符串中的单词时遇到了问题。下面的函数正确地找到添加了重复的单词,但是在删除任何单词后,它会在添加时计算移位的单词。

这是一些代码,“stringAfterModification”被传递参数:

const string = "I went to the mall"
const stringAfterModification = "I went to the mall and left mall" || "I to the mall"
const addedValue = stringAfterModification.split(' ')
        .filter((t, index) => stringAfterModification.split(' ')[stringAfterModification .split(' ').indexOf(t)] !== t
            || string.join(' ').split(' ').indexOf(t) !== index).join(' ');
const removedValue = string.join(' ').split(' ').filter(t => !stringAfterModification .split(' ').includes(t)).join(' ');

我可以过滤掉添加的单词是“and”和“left”,如果我删除某些东西,removedValue 将正确地列出“went”,但是 addedValue 将列出“went”之后的所有内容,因为它们的索引发生了变化。不幸的是,我不能忽略这种情况,因为用户可以添加另一个已经存在的单词,而这里没有问题。无论我是否添加了 ro 删除了某些内容,我该如何解决这个问题,所以 addedValue 和 removedValue 都是正确的?

标签: javascriptarraysstring

解决方案


推荐阅读