Truncation based on element width...?

I’m using the following function to truncate by character count:

            function truncate(str, limit) {
                var chars;
                var i;

                if ( typeof(str) != 'string') {
                    return '';
                }
                
                chars = str.split('');
                
                if (chars.length > limit) {
                    for (i = chars.length - 1; i > -1; --i) {
                        if (i > limit) {
                            chars.length = i;
                        }else if (' ' === chars[i]) {
                            chars.length = i;
                            break;
                        }
                    }
                    chars.push('...');
                }
                return chars.join('');
            }

I found this function in one of the Stack threads and was wondering if it might be possible to retrofit this to do the following:

1.) Check if the second parm is a string. If it is, it’s an element.
2.) Check the width of the element and somehow calculate the amount of truncation being done based on it’s width.

I think it would boil down to performing a check to verify that it’s a string first, but then after that, I’m not sure how character size plays a part nor am I sure how that should be manipulated in regards to the size of the element it’s contained in. I’m thinking that you would take the width of the element and then the width of the text and I guess if the text either breaks or is bigger than the allotted width of the container, truncate the text?

If someone could steer me in the right direction, it would be very appreciated. :slight_smile:

It is a bit longwinded but you could create an image from the text and get the size of that. The problem then becomes how much to shorten the text by but should work with all fonts.

You could use a fixed pitch font which would make the calculations easier but you are then restricted by what fonts you could use.