nodejs-指定長さの断句

1240 ワード

function clause(str: string, long: number) {
       long = long || 200;
  let regExpStr = `\\?|\\?|\\“|\\”|\\"|\\'|\\‘|\\’|\\;|\\;|\\.|\\。|\\!|\\!|\\:|\\:|\\,|\\,|\\、`;
  let strArr = [];

  if (str.length <= long) {
    if (str.replace(new RegExp(regExpStr, "g"), "").trim()) {
      strArr.push(str);
    }
    return strArr;
  }

  let splitPunctuationTmp = str.split(new RegExp(regExpStr));

  let punctuationArr = str.match(new RegExp(regExpStr, "g"));

  let strtmp = "";

  for (let i = 0; i < splitPunctuationTmp.length; i++) {
    strtmp += splitPunctuationTmp[i] + (punctuationArr[i] || "");
    if (
      splitPunctuationTmp[i + 1] != undefined &&
      splitPunctuationTmp[i + 1] != ""
    ) {
      if (strtmp.length + splitPunctuationTmp[i + 1].length > long) {
        if (strtmp.replace(new RegExp(regExpStr, "g"), "").trim()) {
          strArr.push(strtmp);
        }
        strtmp = "";
      } else {
      }
    } else {
      if (strtmp.replace(new RegExp(regExpStr, "g"), "").trim()) {
        strArr.push(strtmp);
      }
      strtmp = "";
    }
  }
  return strArr;
}