13

I have the following mark-up:

<h5>
  <a href="javascript:void(0);">I am a very long title and I need to be shortened</a>
</h5>

How can I make it so that if the h5 text is above a certain number of characters, I get rid of the other characters and replace them with a "..."?

  • 1
    Check out `text-overflow: ellipsis` – https://developer.mozilla.org/en/docs/Web/CSS/text-overflow – helb Apr 03 '17 at 13:08
  • 2
    `...` is called an ellipsis. You can apply them based on physical width, E.g. http://stackoverflow.com/questions/26973570/setting-a-max-character-length-in-css – Alex K. Apr 03 '17 at 13:09

5 Answers5

19

This should work. You have to display the inline element as a block.

Edit: Just realized you want to add dots if the H5 exceeds a number of characters, not if it exceeds a width. I think to do that you will need to use JS - check out the other answer for that.

h5 {
  display: block;
  white-space: nowrap;
  width: 12em;
  overflow: hidden;
  text-overflow: ellipsis;
  color: red; /* This needs to match the color of the anchor tag */
}


a:link {
  color: red;
}
<h5>
  <a href="javascript:void(0);">I am a very long title and I need to be shortened</a>
</h5>
blackandorangecat
  • 1,246
  • 5
  • 18
  • 37
9

You can do this:

var name = $('a').text();
if (name.length > 20) {
    var shortname = name.substring(0, 20) + " ...";
    $('a').replaceWith(shortname);
}
Prarthana Hegde
  • 361
  • 2
  • 7
  • 18
1

If you want to use javascript, you can extend String object by prototyping:

String.prototype.limit = function(length) {
    return this.length > length ? (this.substring(0, length) + '...') : this;
}

var str = 'qwertyuiop';
console.log(str.limit(5)); // qwert...
AliN11
  • 2,387
  • 1
  • 25
  • 40
0
<h5 id="expansion">
  <a id="myLink" href="javascript:void(0);">I am a very long title and I need to be shortened And Also I am a very long title and I need to be shortened</a>
</h5>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>

if($('#myLink').text().length > 20){
    var linkText = $('#myLink').text();
    $('#myLink').html(linkText.substring(0,20)+"...")
    $('#myLink').on("click",function(){
        console.log("linkText :: ",linkText);
        $('#myLink').html(linkText);
    });
}
</script>
Kinjal Akhani
  • 168
  • 12
-2

This one is working

        <h5>
          <a class ="one" href="javascript:void(0);">I am a very long title and I need to be shortened</a>
        </h5>
        <style>
    .one
    {
      white-space: nowrap;
      overflow:hidden;
      text-overflow: ellipsis;
      display:inline-block;
      width : 100px;
    }
</style>

set the width according to your website design

G.Ashok Kumar
  • 1,649
  • 2
  • 13
  • 25