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

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

问题描述

以下面的字符串为例:

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

我想从这个字符串中找到重复的单词,删除所有重复的单词,保留一个单词出现的位置,然后输出修改后的字符串.

在这个例子中是:

var string = "spanner, span, spaniel";

我已经设置了一个 jsFiddle 进行测试:http://jsfiddle.net/p2Gqc/

请注意,字符串中单词的顺序不一致,每个字符串的长度也不一致,因此我认为正则表达式不会在这里完成这项工作.我正在考虑将字符串拆分为数组的方法?但我希望它对客户端尽可能轻巧且速度超快......

解决方案

这样的事情怎么样?

拆分字符串,获取数组,对其进行过滤以删除重复项,然后将它们重新连接起来.

var uniqueList=string.split(',').filter(function(item,i,allItems){返回 i==allItems.indexOf(item);}).加入(',');$('#output').append(uniqueList);

小提琴

对于不支持的浏览器,您可以通过在 js 中添加它来解决它.

参见 过滤器

if (!Array.prototype.filter){Array.prototype.filter = function(fun/*, thisp*/){严格使用";如果(这个 == 空)抛出新的类型错误();var t = Object(this);var len = t.length >>>0;if (typeof fun != "function")抛出新的类型错误();var res = [];var thisp = 参数[1];for (var i = 0; i 

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.

Which in this example would be:

var string = "spanner, span, spaniel";

I've setup a jsFiddle for testing: 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...

解决方案

How about something like this?

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);

Fiddle

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

See 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天全站免登陆