Limit Displayed Selected Items and Show Remaining Count

Up to 5 selected items are displayed by their text and if more than 5 items are selected, I want to show the first 5 items followed by "remaining count + " in a separate span to limit the selected items. refer to the image

image

 function initializeSelect2WithCheckbox(selector) {
        $(selector).select2({
            templateResult: formatSelectionWithCheckbox,
            templateSelection: function(item) {
                return $('<span>').text(item.text);
            },
            closeOnSelect: false,
            allowClear: true
        }).on('select2:select', function(e) {
            var selectedValue = e.params.data.id;

            if (selectedValue === 'all') {
                var allOptions = $(selector).find('option').not('[value="all"]');
                var selectAllChecked = $(e.target).find('option[value="all"]').prop('selected');

                allOptions.prop('selected', selectAllChecked);
                $(selector).trigger('change');
            } else {
                updateSelectAll(selector);
            }
            $(selector).select2('close');
        }).on('select2:unselect', function(e) {
            if (e.params.data.id === 'all') {
                $(selector).val(null).trigger('change'); // Clear all on unselect
            } else {
                updateSelectAll(selector);
            }
        });
    }