skip to Main Content

I want to truncate a word to 50 characters but in 50 characters it should not be an HTML tag. Suppose I have the below HTML:

<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>

Then it should count 50 characters including only "This is a test message This is a test message This is a test message"

And after truncating, it should display like below:

<p>This is a test message</p>This is a test message<p>This</p>

This I want to achieve using jQuery.

2

Answers


  1. Here is my quick solution, you may need to adjust the output format, but this is how you can achieve using jQuery.

    var html = '<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>';
    
    
    // strip HTML tags
    var text = $(html).text(); 
    
    // truncate to 50 characters
    var truncated = text.substring(0, 50); 
    
    // create a copy of the HTML
    var result = $(html).clone().html(truncated);  with the truncated text
    
    if (truncated.length < text.length) { 
      result.append('...');
    }
    console.log(result.prop('outerHTML')); 
    

    Console output:

    "&lt;p&gt;This is a test messageThis is a test messageThis i...&lt;/p&gt;"
    
    Login or Signup to reply.
  2. I don’t think you need jQuery for this. A quick solution would be to loop over every character. If the character is inside < or > characters, then add it to the final string. Otherwise, only add it if the count of characters already added that were outside < or >s is less than 50:

    function shorten(s, maxChars) {
      let short = '';
      let tagFlag = false;
      let i = 0;
      for (const ch of s) {
        if (ch == '>' || ch == '<') {
          tagFlag = !tagFlag;
          short += ch;
        } else if (tagFlag) {
          short += ch;
        } else if (i < maxChars) {
          short += ch;
          i++;
        }
      }
      return short;
    }
    
    console.log(shorten('<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>', 50));

    The only pitfall of this is that tags like the <a> are still included, however, they are empty. Because the extra tags are empty, they won’t show up and it shouldn’t make a difference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search