Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript remove duplicate lines from textarea, but keep (ignore) empty lines

Tags:

javascript

I use this code:

window.removeDuplicateLines = function() {
"use strict";
    var bodyText = $('#text-area').val().split('\n');
    var uniqueText = [];
    $.each(bodyText, function(i, el){
        if($.inArray(el, uniqueText) === -1) {
            uniqueText.push(el);
        }
    });

    document.getElementById('text-area').value = uniqueText.join('\n');
};

from here: Remove Duplicates from JavaScript Array to remove duplicate lines from the textarea.

This code works good, but it removes empty lines also as duplicates.

Question: How can I remove duplicate lines, but keep (ignore) empty lines, with this code?

like image 456
Mik Abe Avatar asked Apr 25 '26 10:04

Mik Abe


1 Answers

You need to see if the entire line has just spaces. To do so you can trim() and then check if length is 0. So change your if check to below

   if($.inArray(el, uniqueText) === -1 || $.trim(el).length === 0) {
        uniqueText.push(el);
    }
like image 148
Rajshekar Reddy Avatar answered Apr 28 '26 01:04

Rajshekar Reddy