js┃将长文本按标点符号分割的尽量长,但不超过指定长度

js┃将长文本按标点符号分割的尽量长,但不超过指定长度

若有更好的方法,希望大佬指教一二

// 使用了lodash库的_findLastIndex和_findIndex方法
const format2Array = (str: string, max: number = 150) => {
    
    
  const REGEXP = /(?<=[,。?!;…])/
  if (str.length < max) {
    
    
    return [str]
  }
  const str1 = str.slice(0, max)
  let index = _findLastIndex(str1.split(''), (i: string) => REGEXP.test(i))
  if (index === -1) {
    
    
    index = _findIndex(str.split(''), (i) => REGEXP.test(i))
  }
  const item1 = [str.slice(0, index + 1)]
  const item2 = index + 1 !== str.length ? format2Array(str.slice(index + 1, str.length), max) : []
  return item1.concat(item2)
}
const CONTENT = '人之初,性本善。性相近,习相远。苟不教,性乃迁。教之道,贵以专。昔孟母,择邻处。子不学,断机杼。窦燕山,有义方。教五子,名俱扬。养不教,父之过。教不严,师之惰。'
format2Array(CONTENT, 15)

运行结果如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44670249/article/details/120912271