gpt4 book ai didi

javascript - 使用 JavaScript 如何将字符串分解为特定长度,同时保留特殊字符?

转载 作者:行者123 更新时间:2023-12-03 07:40:08 25 4
gpt4 key购买 nike

我有一段文本:

George wanted to bake cookies. He asked Mom to help him.

George decided he would bake chocolate-chip cookies. First, Mom had to buy the ingredients. She bought flour, sugar, and chocolate chips. Next, George and Mom mixed together all the ingredients. Finally, they put the cookies in the oven for ten minutes. Last, they let the cookies cool down, and ate them.

"These are delicious!" said George.

我想将其转换为每行最多 50 个字符的数组。

我目前有:

var lines = text.split(/\r|\n/g);
lines.forEach(function (item, index) {
words = item.match(/.{1,50}\b/g);
});

这几乎有效,但它忽略了句点和类似的东西,所以我留下了

George wanted to bake cookies. He asked Mom to
help him

George decided he would bake chocolate-chip
cookies. First, Mom had to buy the ingredients.
She bought flour, sugar, and chocolate chips. Next
, George and Mom mixed together all the
ingredients. Finally, they put the cookies in the
oven for ten minutes. Last, they let the cookies
cool down, and ate them

"These are delicious!" said George.

我做错了什么?

最佳答案

您可以使用空格代替单词边界(在字母和点之间匹配):

例如使用此模式:

/\S(?:.{0,48}\S)?(?!\S)/g

详情:

\S              # all that is not a white-space
(?:.{0,48}\S)? # between 0 and 48 characters followed by a non white character
(?!\S) # not followed by a non-white character (in other words, followed
# by a white space or the end of the string)

另一个优点是该模式避免了前导和尾随空格。

关于javascript - 使用 JavaScript 如何将字符串分解为特定长度,同时保留特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35445715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com