Remove occurrences of duplicate words in a string

前端 未结 9 1994
野性不改
野性不改 2020-11-27 07:37

Take the following string as an example:

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

From this string I would like to find the duplicate

9条回答
  •  暖寄归人
    2020-11-27 08:12

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

提交回复
热议问题