在一个字符串中删除重复出现的词 [英] Remove occurrences of duplicate words in a string

查看:461
本文介绍了在一个字符串中删除重复出现的词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的字符串作为一个例子:

Take the following string as an example:

var string = "spanner, span, spaniel, span";

从这个字符串,我想找到重复的话,删除所有保持的一个词出现的地方重复的,然后再输出修改后的字符串。

From this string I would like to find the duplicate words, remove all the duplicates keeping one occurrence of the word in place and then output the revised string.

在这个例子将是:

var string = "spanner, span, spaniel";

我设置一个的jsfiddle来进行测试: http://jsfiddle.net/p2Gqc/

请注意,字符串中的单词的顺序并不一致,也不是每一个字符串,因此正则表达式是不打算在这里,我不认为做这个工作的长度。我想沿着分割字符串到一个数组的线条的东西吗?但我想它是作为客户端上尽量清淡和超快速...

Note that the order of the words in the string is not consistent, neither is the length of each string so a regex isn't going to do the job here I don't think. I'm thinking something along the lines of splitting the string into an array? But I'd like it to be as light on the client as possible and super speedy...

推荐答案

如何这样的事情?

分割字符串,得到数组,其过滤除去重复的项目,他们一起回来了。

split the string, get the array, filter it to remove duplicate items, join them back.

var uniqueList=string.split(',').filter(function(item,i,allItems){
    return i==allItems.indexOf(item);
}).join(',');

$('#output').append(uniqueList);

小提琴

对于非支持的浏览器,你可以在你的js添加此解决它。

Fiddle

For non supporting browsers you can tackle it by adding this in your js.

请参阅Filter

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

这篇关于在一个字符串中删除重复出现的词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆