gpt4 book ai didi

Javascript - 如何编写递归函数来构建像自动换行这样的字符串数组?

转载 作者:行者123 更新时间:2023-11-28 13:06:29 27 4
gpt4 key购买 nike

我需要逐行构建一个字符串数组。它就像自动换行一样。

我将输入如下文本:

    var inputString = 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration';

我需要数组中的每一行最多包含 38 个字符。我不想在中间分割任何单词,因此如果 38 个字符位于单词中间,则返回到最近的空格字符。

期望的输出:

    var output = [
'There are many variations of passages',
'of Lorem Ipsum available, but the',
'majority have suffered alteration'
];

输出不正确:

'There are many variations of passages '
'of Lorem Ipsum available, but the majo'
'rity have suffered alteration.'

我尝试用空格字符分割输入文本,最终得到以下结果:

var splitInput = [
'There',
'are',
'many'
...
]


function conc(arguments){
if (arguments.length === 0)
return "";
else
return arguments.shift() + conc(arguments);
}

我不知道如何检查参数总数是否为 38 个或更多,如果是则回溯。

最佳答案

你可以使用 string.prototype.match() 来做到这一点

    var inputString = 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration';


let result = inputString.match(/\b.{1,38}\b/g);

console.log(result);

由于正则表达式不重叠,您将得到所需的结果

关于Javascript - 如何编写递归函数来构建像自动换行这样的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154122/

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