首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Javascript中缩短大字符串而不裁剪单词并保存到数组中

在Javascript中,可以使用以下方法来缩短大字符串而不裁剪单词并保存到数组中:

  1. 使用正则表达式和split()方法:可以使用正则表达式将字符串按照空格分割成单词数组,然后根据指定的长度将单词拼接成新的字符串。代码示例如下:
代码语言:txt
复制
function shortenString(str, maxLength) {
  if (str.length <= maxLength) {
    return [str];
  }
  
  const words = str.split(/\s+/); // 使用正则表达式按照空格分割字符串
  let shortenedString = '';
  let currentLength = 0;
  const result = [];
  
  for (let i = 0; i < words.length; i++) {
    if (currentLength + words[i].length <= maxLength) {
      shortenedString += words[i] + ' ';
      currentLength += words[i].length + 1;
    } else {
      result.push(shortenedString.trim());
      shortenedString = words[i] + ' ';
      currentLength = words[i].length + 1;
    }
  }
  
  result.push(shortenedString.trim());
  return result;
}

const longString = "This is a long string that needs to be shortened without cutting words and saved into an array.";
const maxLength = 20;
const shortenedArray = shortenString(longString, maxLength);
console.log(shortenedArray);

上述代码中,我们首先将字符串按照空格分割成单词数组。然后,我们使用一个循环来遍历单词数组,将单词逐个拼接成新的字符串,并根据指定的最大长度进行判断。如果当前拼接的字符串长度不超过最大长度,则继续拼接;否则,将当前拼接的字符串保存到结果数组中,并重新开始拼接新的字符串。最后,将最后一个拼接的字符串也保存到结果数组中。最终,返回结果数组。

  1. 使用递归方法:可以使用递归方法来逐步缩短字符串,直到满足指定的长度要求。代码示例如下:
代码语言:txt
复制
function shortenString(str, maxLength) {
  if (str.length <= maxLength) {
    return [str];
  }
  
  let shortenedString = str.substring(0, maxLength);
  let lastSpaceIndex = shortenedString.lastIndexOf(' ');
  
  if (lastSpaceIndex !== -1) {
    shortenedString = shortenedString.substring(0, lastSpaceIndex);
  }
  
  const remainingString = str.substring(shortenedString.length).trim();
  const result = [shortenedString];
  
  return result.concat(shortenString(remainingString, maxLength));
}

const longString = "This is a long string that needs to be shortened without cutting words and saved into an array.";
const maxLength = 20;
const shortenedArray = shortenString(longString, maxLength);
console.log(shortenedArray);

上述代码中,我们首先判断字符串的长度是否小于等于最大长度,如果是,则直接返回包含原字符串的数组。否则,我们使用substring()方法将字符串截取到指定的最大长度,并找到最后一个空格的位置。如果找到了空格,则将截取的字符串重新赋值为截取到空格之前的部分。然后,我们将剩余的字符串继续进行递归调用,直到满足长度要求。最后,将所有截取的字符串保存到结果数组中,并返回结果数组。

这两种方法都可以在Javascript中缩短大字符串而不裁剪单词并保存到数组中。具体使用哪种方法取决于实际需求和性能要求。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券