user2101411 user2101411 - 1 month ago 10
jQuery Question

commas are not being joined with a space after them jquery

I am trying to add a space after a comma for each string in an array with jQuery. I managed to retain non unique values from repeating themselves but I am now faced with the commas not having a space after them even though I have used the join method. Here is my code:

function unique(list) {
var result = [];

$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) {
result.join(", ");
result.push(e);
}
});

// sort the elements
result.sort();

return result;
}

$('#filetext').text(function(i, original) {
var rfile = path.split('/').pop() + ',' + original;

rfile = rfile.replace(/,+$/, "");

// split the files by a comma
var arr = rfile.split(',');

return unique(arr);
});


The result however is string1,string2 and I would like to get it to be string1, string2.

Any help would be appreciated.

Thanks.

Updated function code -

function unique(list) {
var result = [];

$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) {
result.push(e);
}
});

// sort and join the elements
result.sort();

return result.join(", ");
}

Answer

Based on convo in comments, trim the text, return with the join()

function unique(list) {
    var result = [];

    $.each(list, function(i, e) {
        var txt = $.trim(e);
        if ($.inArray(txt, result) == -1) {
            result.push(e);
        } 
    });

    // sort and join the elements
    result.sort();

    return result.join(", ");
}

or change your split to handle the whitespace.

rfile.split(/\s*,\s*/g);