【问题标题】:build array based on a text with character delimiter基于带有字符分隔符的文本构建数组
【发布时间】:2021-12-23 11:37:43
【问题描述】:

我很难创建一个通用函数,其中输入是包含大量或少量文本的字符串,而输出是一个数组,我在这种复杂性方面遇到了很多麻烦,但是每个位置数组必须最多包含 125 个字符,并且不能有断字,例如,如果有任何最终单词必须将 125 个字符传递到数组的下一个位置。

例子:

输入值:`var text =" Lorem Ipsum is simply a text simulation of the printing and printing industry, and has been in use since the 16th century, when an unknown printer took a tray of typefaces and shuffled them together to make a type model book Lorem Ipsum survived not only five centuries but also the leap into desktop publishing, remaining essentially unchanged It became popular in the 1960s when Letraset launched decals containing passages of Lorem Ipsum, and more recently when is now integrated with desktop editing software like Aldus PageMaker."`

输出值不正确:`[ "Lorem Ipsum is simply a text simulation of the printing and printing industry, and it has been in use since the century," "XVI, when a printer discovered a type tray and shuffled them together to make a typeface template book."]`

请注意,由于“世纪”一词,数组的 0 位置已从 125 变为。

正确的输出值:`[" Lorem Ipsum is simply a text simulation of the printing and printing industry, and has been in use since the "," 16th century, when an unknown printer took a tray of typefaces and shuffled them to make a book of models of "," types. Lorem Ipsum survived not only five centuries, but also the leap into desktop publishing, remaining ", ...]`

【问题讨论】:

  • 在空间上拆分整个字符串,然后开始加入,控制每个项目的最大长度。

标签: javascript arrays angularjs string frontend


【解决方案1】:

您可以使用正则表达式 .{1,125}\b 贪婪地搜索 1 到 125 个字符,后跟单词边界:

const regex = /.{1,125}\b/g;
var text =" Lorem Ipsum is simply a text simulation of the printing and printing industry, and has been in use since the 16th century, when an unknown printer took a tray of typefaces and shuffled them together to make a type model book Lorem Ipsum survived not only five centuries but also the leap into desktop publishing, remaining essentially unchanged It became popular in the 1960s when Letraset launched decals containing passages of Lorem Ipsum, and more recently when is now integrated with desktop editing software like Aldus PageMaker.";

console.log(text.match(regex));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多