JavaScript文本截断脚本故障求助:展开时字符重复及空格异常
Fix for JavaScript Text Truncation Issue (Word Splitting & Duplicate Characters)
I see exactly what's going wrong here—your current script is cutting text mid-word and causing duplicate characters because of how it splits the content. Let's break down the issues and fix them step by step:
1. The Root Problems
- Mid-word truncation: You're slicing the text directly at
showChar(400), which often lands in the middle of a word (like splitting "Berücksichtigung" into two parts). - Duplicate characters: Your code uses
content.substr(showChar-1, ...)for the hidden part, which includes the last character of the truncated preview again—so when you expand, that character gets doubled. - Unintended spaces: The extra
in your HTML template can create weird spacing when combining the truncated and hidden content.
2. Fixed Script
Here's the revised code that addresses all these issues:
$(document).ready(function() { var showChar = 400; var ellipsestext = "..."; var moretext = "Mehr"; var lesstext = "Weniger"; $('.more').each(function() { var content = $(this).html(); if (content.length > showChar) { // Find the last space before showChar to avoid mid-word cuts var truncateIndex = content.lastIndexOf(' ', showChar); // Fall back to showChar if no space found (edge case for long words) truncateIndex = truncateIndex === -1 ? showChar : truncateIndex; var c = content.substr(0, truncateIndex); var h = content.substr(truncateIndex); // No need to subtract 1 here // Clean up the HTML template to avoid extra spaces var html = c + '<span class="moreelipses">' + ellipsestext + '</span>' + '<span class="morecontent"><span>' + h + '</span> ' + '<a href="" class="morelink">' + moretext + '</a></span>'; $(this).html(html); } }); $(".morelink").click(function(e) { e.preventDefault(); // Better than return false for modern JS if ($(this).hasClass("less")) { $(this).removeClass("less").html(moretext); } else { $(this).addClass("less").html(lesstext); } $(this).parent().prev().toggle(); $(this).prev().toggle(); }); });
3. Key Improvements
- Word-safe truncation: Uses
lastIndexOf(' ', showChar)to find the nearest space before the 400-character limit, so we always cut at the end of a word. - Fixed duplicate characters: Changed
content.substr(showChar-1, ...)tocontent.substr(truncateIndex)—this grabs everything after the truncated preview without repeating characters. - Cleaner spacing: Removed the unnecessary
between the ellipsis and hidden content to avoid unintended gaps. - Modern event handling: Replaced
return falsewithe.preventDefault()for better practice.
4. Edge Case Handling
If you have a single word longer than 400 characters (unlikely, but possible), the script falls back to cutting exactly at 400 characters instead of breaking entirely.
This should resolve both the word-splitting issue and the duplicate character problem you're seeing!
内容的提问来源于stack exchange,提问作者Jeremy Tai
相关产品推荐
相关产品推荐

