Trimming Text with JQuery

My goal was to truncate a string and add an ellipsis at the end using jQuery, but my code doesn't seem to be working as intended.

Below is the jQuery code I wrote:

$(".link-content > h4").each(function(){
    var len = $(this).text().length;
    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>

Answer №1

Save the original text into a variable, and if it exceeds 26 characters in length, truncate it to 26 characters and add "..." at the end:

$(".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>

Answer №2

Below is a snippet demonstrating how to truncate a string and append '...' for any truncated content. There are examples for both a large string (big) that gets truncated and a small string (small) that remains unchanged. It looks like you have the hang of it.


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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the discrepancy between 1px and 0px padding on floating divs in various web browsers?

Take a look at this HTML example - the only variation is padding-top:0px; vs padding-top:1px; However, in the second example, the div is shifted by a completely different amount? <div style="clear: both; margin:0px; padding-top:0px; border: 0px"> ...

Triggering a JQuery event to switch between tabs

Currently, I am in the process of developing a web application that incorporates nav-tabs from Bootstrap. These nav-tabs consist of 4 different tab-contents. My main concern lies in determining which nav-tab the user has selected among the 4 tabs and updat ...

Rgd: Double-Sided Horizontal Slide Control

While browsing the internet, I came across several examples of horizontal sliders with adjustable values. For example, if I set the maximum value as 100 and move the slider 10 sectors to the left, each sector would decrease by 10. What I am trying to ach ...

Breaking the line when combining an image_tag and text in a Rails navbar

Looking for some help combining a logo and brand name in my Bootstrap navbar. I'm running into an issue where there is a line break separating the logo and text. Can someone provide some assistance? <%= link_to image_tag("brand_logo.png") + " Bran ...

How are these background images able to remain in a fixed position like this?

Trying to name this question correctly was a bit tricky. Hopefully I got it right. I have a new client and they want their website to have a similar feel to . If you check out the index page and scroll down, there's this cool 'smooth animation& ...

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

The H1 tag is mysteriously displaying padding or margin on the bottom, despite not being set

Despite not setting any padding or margin for the H1 tag, it still appears to have some spacing at the bottom. After applying a margin and padding of 0 to both the h1 tag and the text below it, I am still facing an issue where the text doesn't align ...

Tips for locating and clicking a specific table element using Selenium

Is there a way to dynamically click the link associated with the label in this specific td? I am able to locate the link using the onclick method, however, the label name changes periodically from HemoGlobin A1C to HGB A1c, etc. and there is no unique ID ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Tips for keeping the scroll position of a bootstrap table when reloading the page

Displayed below is a bootstrap table with specific features. <div class="row"> <table id="question-selection" class="table table-sm table-hover table-wrapper"> <tbody> {% for placer in chapter_questions %} ...

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

Toggle the visibility of multiple divs by clicking on other divs

I have implemented a script on my webpage to toggle the visibility of certain divs by clicking on anchor tags. I found a solution that seems perfect for my needs, but unfortunately it is not working when I try to integrate it into my own website. I suspec ...

What causes the toggle effect in my jQuery onclick function to alternate between on and off when the initialization is repeated multiple times?

I am facing an issue with my website where icons/buttons trigger a menu when clicked. I need to load more data by adding more buttons, so I tried re-initializing the existing buttons using a jQuery onclick function whenever the number of buttons changes. ...

Developing a Customized Styling Guide Using Node.JS and User Specifications

Seeking a method to generate a personalized user style sheet utilizing input from users. Users can choose options like background colors, and the app will generate a custom style sheet based on their selections. Their input will be captured through HTML in ...

Elements listed are often ignored by HTML

My website sends a URL and xpath query to the server in order to extract data from the URL based on the xpath query. While it is functioning properly, I am encountering a singular issue. When I specify an xpath query for href,text, it displays a list of a ...

Issues with the proper functionality of the .ajax() method in Django

I'm currently facing an issue with my Ajax code while trying to interact with the database in order to edit model instances. I noticed that the first alert statement is functioning correctly, however, the subsequent alert statements are not working as ...

Calling @Url.Action multiple times does not consistently return the same results

It appears that there is a discrepancy related to jQuery/MVC3 that I have yet to figure out. If anyone could shed light on this matter, it would be greatly appreciated. Whenever I invoke an action routine multiple times, the @Url.Action routine generates ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

Can I use JavaScript to generate an element similar to <ion-icon name="heart"></ion-icon>?

Currently, I am utilizing a website called to incorporate icons into my buttons. It is quite straightforward with HTML when introducing a new element containing the icon. All you need to do is define a button and insert this code within it: ion-icon name= ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...