如何更改此子字符串逻辑,以便在单词结束时最接近 JS 中的结束值时停止?

How to change this substring logic so it will stop when the word is ended closest to the ending value in JS?

我有一个字符串,当它超过 50 个字符时需要将其剪切。问题是它删了最后一个字。

 showName(name) {
      if (name.length < 50) {
        return name
      } else {
        return name.substring(0, 50) + '...'
      }
    },

我怎样才能完成最后一个单词?

您可以对字符串进行反向循环,直到遇到 space 和那里的拼接。一个这样的:

function truncateFullWord(string, maxLen) {
  for (let i = maxLen; i >= 0; i--) {
    if (string[i] === ' ') return string.substring(0, i) + '...';
  }
}

所以你现有的代码有四个你会写成

 showName(name) {
  if (name.length < 50) {
    return name
  } else {
    // use loop
    return truncateFullWord(name, 50);
    // use lastIndexOf
    const trimmed = string.substring(0, maxLen);
    return trimmed.substring(0, trimmed.lastIndexOf(' ')) + '...';
  }
}

这是一种有点幼稚的方法,不能很好地处理 non-space 中断,但它可能已经足够好了。

function showName(name) {
  if (name.length < 50) {
    return name
  } else {
    const short = name.substring(0, 50)
    const shortWords = short.split(/\b/)
    const lastShortWord = shortWords[shortWords.length - 1]
    const words = name.split(/\b/)
    const adjWord = words[shortWords.length - 1]
    if (lastShortWord !== adjWord) {
      return short.substring(0, short.lastIndexOf(' ')) + '...'
    }
    return short + '...'
  }
}

console.log(showName('A really long name that should span more than 50 characters but not cut in the middle of the last word in the allowed length'))