首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在保留标点符号的同时拆分字符串

在保留标点符号的同时拆分字符串
EN

Stack Overflow用户
提问于 2022-05-23 17:42:49
回答 1查看 36关注 0票数 -1

我有一个大约1500到2000字符的文本。这个文本应该被分割成文本块,每个文本大约有400个字符(不需要精确的400个字符)。然而,它不应该只是分裂文本每400个字符,但分裂文本只有在有一个句号的地方。因此,基本上把一个大文本分成几块,而不破坏标点符号。

知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-23 18:03:05

我们可以试着减价

我在这里做了500,因为你的短信是< 400

代码语言:javascript
运行
复制
let str = `I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation.`

let nextPunct = str.indexOf(".")
const lines = str.split(/\.\s+/)
  .reduce((acc, line, i) => {
    if (i === 0) acc.push(line)
    else if ((acc[acc.length - 1].length + line.length) > 500) acc.push(line)
    else acc[acc.length - 1] += ". " + line;
    return acc
  }, [])
const res = lines.join(".\n")

console.log(res, lines.map(line => line.length))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72352758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档