在Javascript中的截断词后截断字符串

use*_*090 3 javascript

我想在javascript中某些字符长度后截断字符串。当达到字符长度时,不应在单词中间切入字符串,而应将单词补全,然后截断字符串。我尝试过的直到现在都在切割词之前切割了字符串。我想在返回的字符串中包含切割词。这是我的代码:

function truncateString(yourString, maxLength) {
  var trimmedString = yourString.substr(0, maxLength);
  trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
  return trimmedString;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用以下参数调用此函数时:

truncateString('The quick brown fox jumps over the lazy dog',6)
Run Code Online (Sandbox Code Playgroud)

输出为'The' rather than 'The quick

请指出我需要更改的地方。谢谢

adi*_*iga 5

您可以maxLength使用的第二个参数搜索后面的立即空间索引indexOf

function truncateString(yourString, maxLength) {
  // get the index of space after maxLength
  const index = yourString.indexOf(" ", maxLength);
  return index === -1 ? yourString : yourString.substring(0, index)
}

const str = 'The quick brown fox jumps over the lazy dog';

console.log(truncateString(str,6))
console.log(truncateString(str,10))
console.log(truncateString(str,100))
Run Code Online (Sandbox Code Playgroud)