You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于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:

  1. Truncate strings to a specified maximum length, including the "..." ellipsis
  2. Avoid cutting words mid-way when possible (e.g., truncate to the end of a full word before adding ellipsis)
  3. 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:

  1. truncateString("A-tisket a-tasket A green and yellow basket", 11) → returns "A-tisket..." (matches your expectation)
  2. truncateString("Peter Piper picked a peck of pickled peppers", 14) → returns "Peter Piper..." (perfect match)
  3. If you do want to add ellipsis even when maxLength equals the original string length, just delete the first if block. The function will then truncate to originalLength - 3 characters and add ellipsis, which aligns with your third example.

内容的提问来源于stack exchange,提问作者Dan Petrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:47:45