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

Properly managing the Ajax.BeginForm OnSuccess event

I am facing an issue with my code that calls the 'SaveNewSoftware' method. This method will return true if there is no existing software found, and false if software with the same name already exists. My problem is that even when the server call ...

JavaScript Functions for Beginners

I'm currently facing some challenges with transferring the scripts and HTML content from the calendar on refdesk.com. My task involves moving the JavaScript to a separate stylesheet and utilizing those functions to replicate the calendar on an HTML pa ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

What's the best way to constrain a draggable element within the boundaries of its parent using right and bottom values?

I am currently working on creating a draggable map. I have successfully limited the draggable child for the left and top sides, but I am struggling to do the same for the right and bottom sides. How can I restrict the movement of a draggable child based o ...

The Angular factory function was unable to be initialized

I recently started learning how to integrate Angularjs with ROR using this helpful tutorial While working on adding a new function to retrieve all posts from the database, I encountered a problem. The page no longer loads when I run the code and the HTML ...

Exploring the Terrain: Troubleshooting Meteor CSS with Twitter Bootstrap

Recently, I have encountered an issue that perplexes me - I am unable to debug less code in my meteor app when the twbs:boostrap package is present. Interestingly, everything works fine when I remove it, but as soon as I add it back, the CSS seems to be co ...

Storing information in a database

Need help troubleshooting why my form isn't saving data to the database. <div class="container"> <div class="row" style="margin-top:200px;"> <form ENCTYPE="multipart/form-data" ACTION="upload.php" METHO ...

How to Automatically Close an Ajax Modal Popup After Executing Code in ItemCommand in ASP.Net

I am currently facing an issue with closing a ModalPopup after a code sequence is executed. The situation at hand involves coding a filebrowser for the company and everything seems to be working fine except for the downloading of files. I have implemented ...

What is the best way to make a dropdown button on a top navigation bar show as active using Semantic-ui?

I searched through the Semantic-ui documentation, but I couldn't find clear instructions on how to designate a dropdown item as 'active' (highlighted without being opened) in my top navbar menu, similar to regular items. The 'active&ap ...

Leveraging SVG filters for enhancing text with unique borders

I recently discovered a helpful tip on adding a background to text in SVG using a source. However, I am still unsure how to incorporate a border around the text. <svg width="100%" height="100%"> <defs> <filter x="0" y="0" width="1" ...

retrieve the Jquery progress bar's current value

Having trouble determining the value of the progress bar in order to increase it by a percentage with each step. No matter what I attempt, I keep getting errors such as 'undefined' or 'method cannot be called before object instantiation.&apo ...

Is there a way to iterate through identical sections of HTML using BeautifulSoup?

Looking to extract information from each of the "item watching" elements within the "items" class. Currently facing a challenge where using the find method only retrieves HTML for the first occurrence of "item watching". Aiming to avoid utilizing find_all ...

Show a specific portion of an extremely large .svg image file using Angular.js directive with the help of javascript or css

Currently, I am facing a challenge with a large map image (3000x8000px) in .png format that I have converted to .svg for data visualization purposes. I am struggling to find a way to display a specific small section of this map.svg file on an HTML page u ...

The use of the `foreach` loop

How can I change the position index to start at 1 instead of 0? I want the first name to be listed as number 1 and end at number 50. Is there a way to fix this issue? Here is my code: <html> <head> <title>SEATPLAN</title> &l ...

Manipulate Attributes in Javascript

Having an issue here - I'm trying to use JavaScript to set some attributes. for(i=0;i<div_navi.childNodes.length;i++){ if(div_navi.childNodes[i].nodeName =="SPAN"){ div_navi.childNodes[i].setAttribute("onclick","g ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Ways to incorporate color gradients into the corners of CSS cards

Below is an example of a basic bootstrap card: Example 1: https://i.stack.imgur.com/DK2Sz.png I attempted to draw blue and green colors side by side, but was only successful in drawing blue as shown below: Example 2: https://i.stack.imgur.com/CcSzP.png ...

Showing the heading again after a new page starts

Currently, I am using WeasyPrint to generate a document and facing an issue with long sections that may span multiple pages. When a section breaks across pages, the name of the section does not display after the page break as intended. The following examp ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

Submit your information discreetly

Is there a way to submit a form to an external website without it causing the page to reload? I am working on automatically logging users into their Google account without interrupting their browsing experience. The following code snippet allows me to pr ...