关于str.endsWith("-")返回异常及字符串截断函数的技术问询
Hey there, let’s break down your two tech issues step by step—I’ve run into both of these myself before, so I know how tricky they can be!
1. Why doesn’t str.endsWith("-") return true?
The #1 culprit here is almost always hidden trailing characters you can’t see in your code. Think stray spaces, newlines (\n), tabs (\t), or even non-printable Unicode characters. For example, if your string is actually "my-string- " (with a trailing space), endsWith("-") will return false because the last character is a space, not a hyphen.
Rarely, it could also be an encoding issue: if the "hyphen" in your string is actually an en dash (–) or em dash (—) instead of the standard ASCII hyphen (-), the check will fail because they’re different Unicode characters.
How to debug this quickly:
Spit out some details about the string to see what’s really going on:
const str = "your-problem-string-here"; console.log(`String length: ${str.length}`); // If this is longer than you expect, there's extra characters console.log(`Last character char code: ${str.charCodeAt(str.length - 1)}`); // A standard hyphen is char code 45; space is 32, newline is 10 console.log(`Wrapped string: "${str}"`); // Trailing spaces/newlines will show up here
Fixes:
- If trailing whitespace is the issue, trim it first (note
trim()removes all leading/trailing whitespace, not just spaces):str.trim().endsWith("-"); - If you only want to strip trailing whitespace (not leading), use a regex:
str.replace(/\s+$/, "").endsWith("-"); - If it’s a character mismatch, replace any non-standard hyphens with the ASCII version:
str.replace(/[–—]/g, "-").endsWith("-");
2. Fixing your truncateString function
First, let’s lock in the requirements from your examples—they tell us exactly what the function needs to do:
- Truncate strings to a specified maximum length, including the
"..."ellipsis - Avoid cutting words mid-way when possible (e.g., truncate to the end of a full word before adding ellipsis)
- Edge cases: handle short maximum lengths where we can’t fit a full word + ellipsis
Your third example seems a bit odd (truncating even when the max length equals the original string’s length)—I’m guessing that’s a typo, but I’ll build the function to handle both scenarios (you can tweak it easily if needed).
Here’s a function that matches your expected outputs:
function truncateString(str, maxLength) { // If the string is already shorter than/equal to maxLength, return it as-is (remove this line if you always want ellipsis) if (str.length <= maxLength) { return str; } // If maxLength is 3 or less, we can't fit a word + ellipsis—just truncate directly if (maxLength <= 3) { return str.slice(0, maxLength) + "..."; } // Reserve 3 characters for the ellipsis const truncateTarget = maxLength - 3; // Find the last space before our truncate target to avoid cutting mid-word const lastSpaceIndex = str.lastIndexOf(" ", truncateTarget); // If there's no space (single long word), just truncate to the target length const truncatedContent = lastSpaceIndex === -1 ? str.slice(0, truncateTarget) : str.slice(0, lastSpaceIndex); return truncatedContent + "..."; }
Testing it against your examples:
truncateString("A-tisket a-tasket A green and yellow basket", 11)→ returns"A-tisket..."(matches your expectation)truncateString("Peter Piper picked a peck of pickled peppers", 14)→ returns"Peter Piper..."(perfect match)- If you do want to add ellipsis even when maxLength equals the original string length, just delete the first
ifblock. The function will then truncate tooriginalLength - 3characters and add ellipsis, which aligns with your third example.
内容的提问来源于stack exchange,提问作者Dan Petrow

