Mark Gerryl Mirandilla
Mark Gerryl Mirandilla

Reputation: 823

jQuery: Remove duplicate string on textarea

Im working a form which I need to make all string unique.

The code is working fine, but problem is when I make duplicates in new line, the code doesn't work.

I hope you understand me.

Thanks.

CODEPEN

$(document).ready(function(){
  $('button').click(function(){
  var data = $('textarea').val();
	var arr =  $.unique(data.split(' '));
	    data = arr.join(' ');
	$('textarea').val(data);
  });
});
div{
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <textarea name="" id="" cols="30" rows="10"></textarea>
<br>
<button>Remove Duplicates</button>
</div>

Upvotes: 3

Views: 1570

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

https://api.jquery.com/jQuery.unique/

Note that this only works on arrays of DOM elements, not strings or numbers.

You can easily do it without a library with .filter:

$(document).ready(function(){
  $('button').click(function(){
    var data = $('textarea').val();
    var result = data.split(/\s/g).filter((word, i, arr) => arr.indexOf(word) === i);
    $('textarea').val(result.join(' '));
  });
});
div{
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <textarea name="" id="" cols="30" rows="10"></textarea>
<br>
<button>Remove Duplicates</button>
</div>

Upvotes: 3

Related Questions