0

I have a string placed inside the tag and I wanted to truncate it and add an ellipsis at the end of the truncated string. I coded this using jquery and it seems my code doesn't work on my end.

here is my jquery code:

$(".link-content > h4").each(function(){
    var len=$(this).text().lenght;
    var str=$(this).text().substr(0,26);

    var lastIndexOf=str.lastIndexOf();

    if(len>26){
        $(this).text(str.substring(0, lastIndexOf)+"...");
    }
});
<div class="links">
    <span>FACEBOOK</span>
    <div class="link-content">
         <h4>Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
           Etiam lacus tellus, tristique congue pellentesque ac, semper eu 
           d iam.</h4>
    </div>
</div>
4
  • 1
    To start with, .lenght; won't work Commented Apr 1, 2019 at 2:41
  • so how do we get the lenght of the string? @CertainPerformance Commented Apr 1, 2019 at 2:42
  • length, not lenght Commented Apr 1, 2019 at 2:44
  • my bad. had a little typo. thank you though.. @ThumChoonTat Commented Apr 1, 2019 at 2:49

2 Answers 2

1

Extract the original text into a variable, and if its length is greater than 26, set the text to that original text with slice(0, 26) called on it, and concatenated with ...:

$(".link-content > h4").each(function(){
    const origText = $(this).text();
    if (origText.length > 26) {
        $(this).text(origText.slice(0, 26) + '...');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="links">
    <span>FACEBOOK</span>
    <div class="link-content">
         <h4>Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
           Etiam lacus tellus, tristique congue pellentesque ac, semper eu 
           d iam.</h4>
    </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Here's some example code of how to quickly truncate and add '...' for any string that was truncated. There is a one that will truncate (big) and one that will not (small). I think you seem to have the rest of it down.


var big = '1234567890123456789012345678901234567890';
var small = '1234567890';
var big_truncated = big.substr(0,26);
var small_truncated = small.substr(0,26);

big_truncated += (big.length > 26)?'...':'';
small_truncated += (small.length > 26)?'...':'';

console.log(big_truncated);
console.log(small_truncated);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.