【问题标题】:How do I remove duplicate words in a string in JavaScript?如何在 JavaScript 中删除字符串中的重复单词?
【发布时间】:2020-02-15 21:02:00
【问题描述】:

我一直在尝试从字符串中删除重复的单词,但它不起作用。

我有当前字符串:

const categories = 'mexican, restaurant, mexican, food, restaurant'

我想要这样的结果:

const x = 'mexican restaurant food'

我尝试了以下方法:

const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();

这是给我的:

uniqueList = 'chinese restaurant chinese food restaurant'

上面的代码有什么问题?

【问题讨论】:

  • 将字符串转换为数组并将其放入Set。这将自动为您提供一个唯一列表,您可以将其转换回字符串。
  • 不带参数调用split 只会返回一个包含整个字符串的单例数组。您应该拆分空格字符。

标签: javascript arrays string


【解决方案1】:

我喜欢将Set 用于这种目的。阅读文档:

Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。

这对你有用:

const categories = 'mexican, restaurant, mexican, food, restaurant'.split(', ');

const unique = Array.from(new Set(categories));

console.log(unique);

console.log(unique.join(' '));

希望对你有帮助!

【讨论】:

    【解决方案2】:

    在您使用的String.prototype.split(separator) 方法中,如果缺少分隔符,将返回包含一个元素的数组 - 源字符串。所以在你的代码中应该是.split(' ') 而不是.split()。 但最好使用.split(', ') 而不使用const x = categories.replace(/,/g, '');。甚至你也可以.split(/\s*,\s*/),这样你就不必关心空间了。 加入默认使用 ',' 作为分隔符。所以你应该写.join(' ')

    【讨论】:

      【解决方案3】:

      const categories = 'mexican, restaurant, mexican, food, restaurant';
      
          const uniqueList = categories
            .split(', ') // split the string when a comma + space is found
            .filter((currentItem, i, allItems) => {
              return i === allItems.indexOf(currentItem);
            }) // filter out duplicates
            .join(' '); // rejoin array to string
            
       console.log( uniqueList );

      【讨论】:

        【解决方案4】:

        这可以在一行中完成。试试下面的代码:

        const categories = 'mexican, restaurant, mexican, food, restaurant';
        let result = [...new Set(categories.split(", "))].join(" ");
        

        输出:“墨西哥餐厅食物”

        输出将是你想要的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-14
          • 1970-01-01
          • 2013-12-15
          • 2013-08-11
          • 2018-07-31
          • 2013-05-26
          相关资源
          最近更新 更多