Monday 30 December 2019

How to trim off last character in an Array - jQuery



so today I have an Array with several strings in them, all ending with , example: jazz, latin, trance,




I need to remove the , off the last element in the Array. Searching Stackoverflow I found several answers and tried the code below, but no luck so far :(



// How I'm generating my Array (from checked checkboxes in a Modal)
role_Actor = [];
$('.simplemodal-data input:checked').each(function() {
role_Actor.push($(this).val());
});

// roleArray = my Array

var lastEl = roleArray.pop();
lastEl.substring(0, lastEl.length - 1);
roleArray.push($.trim(lastEl));


// My function that displays my strings on the page
$.each(roleArray, function(index, item) {
$('.'+rowName+' p').append(item+', ');
});


// Example of the Array:
Adult Animated, Behind the Scenes, Documentary,


Thanks for taking a look!






Thanks @Claire Anthony! for the fix!!!


Answer




You forgot to assign lastEl before putting it back in to roleArray:



lastEl = lastEl.substring(0, lastEl.length - 1);



As the comments suggest, and as you're just using this for display purposes, you should remove the commas from the elements in roleArray and use the join method, like so:



var roleArray = ['latin', 'jazz', 'trance'];
$('#example').append(roleArray.join(', '));

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...