Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

remove string duplicates

Status
Not open for further replies.

moley

IS-IT--Management
Mar 26, 2002
95
GB
i'm trying to remove the duplcate entries from the example string below:

var myString ="log177, log177, log277, log178"

what's the simplest way of doing this??

Thanks
 
How about this?
Code:
var data = "log177, log177, log277, log178";
function contains(str)
{
  for (var i=0; i<this.length; i++)
  {
    if (this[i] == str)
      return true;
  }
  return false;
}
Array.prototype.contains = contains;

function removeDuplicates(str)
{
  var d = str.split(", ");
  var tmp = new Array();
  for (var i=0; i<d.length; i++)
  {
    if (!tmp.contains(d[i]))
      tmp.push(d[i]);
  }
  return temp.join(", ");
}

alert(removeDuplicates(data)); // test


--Chessbot

"In that blessed region of Four Dimensions, shall we linger on the threshold of the Fifth, and not enter therein? Ah, no! [...] Then, yielding to our intellectual onset, the gates of the Sixth Dimension shall fly open; after that a Seventh, and then an Eighth -- --" Flatland, A. Square (E. A. Abbott)
 
chessboot's methodis the best, but i simply couldnt control myself from using RegExp:
Code:
<script>
var myString ="log1, log5, log25, log2, log5874, log2, log2,"

i=0
while(myString.match(/(log[\d]+),(.*)\1,/g))
{
	i++
	status=i
	myString=myString.replace(/(log[\d]+),(.*)\1,/g,"$1,$2,")
}
myString=myString.replace(/(\s+,)+/g,",")
myString=myString.replace(/(,+)/g,",")
alert(myString)
</script>

try it out...

Known is handfull, Unknown is worldfull
 
Thanks ChessBot but i cant get the code to work. The contains function always returns false.

Any ideas??
 
how about mine???

Known is handfull, Unknown is worldfull
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top