JS: Add ellipsis if string length exceeded 50 characters

Is it possible to use ternary operator to add ‘…’ if string exceeds 50 characters?

I tried it like this but it doesn’t work.

{post.title.substring(0, 50) + post.title.length > 50
                    ? '...'
                    : ''}

Any suggestion?

16 thoughts on “JS: Add ellipsis if string length exceeded 50 characters”

  1. The conditional operator¹ is fairly greedy. To have it apply only to the part of your expression after the +, you need parentheses (the grouping operator):

    {post.title.substring(0, 50) + (post.title.length > 50
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−^
                        ? '...'
                        : '')
    // −−−−−−−−−−−−−−−−−−−−−^
    }
    

    But you might consider using CSS for this, rather than JavaScript. See text-overflow: ellipsis. You’ll probably need white-space: nowrap and overflow: hidden; as well:

    .limit {
        max-width: 20em;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }
    <div>With limit:</div>
    <div class="limit">Now is the time for all good men to come to the aid of their country</div>
    <div>Without limit:</div>
    <div>Now is the time for all good men to come to the aid of their country</div>

    ¹ ? : is a ternary operator (an operator accepting three operands), and for the moment it’s JavaScript’s only ternary operator, but there could be others in the future. Its name is the conditional operator.

    Reply

Leave a Comment