gpt4 book ai didi

javascript - 使用最大字符拆分字符串

转载 作者:行者123 更新时间:2023-12-03 17:19:11 24 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.

2年前关闭。




Improve this question




当这个字符串有超过 30 个字符时,我想拆分一个字符串,但我不想要任何拆分词。

我的代码实际上正在运行,但我不知道它是否会更好,我认为它可以更简单、更快。

let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet ligula arcu, ut ullamcorper lacus porttitor in. Nulla consequat viverra cursus. Curabitur sit amet libero nec velit sagittis vulputate sit amet vel lorem. Nam consectetur quam est, non semper ipsum porttitor et. Pellentesque tempor eros eget urna efficitur, nec malesuada ipsum laoreet. Curabitur dictum eros quis semper ultrices. Aliquam nisl ante, sodales nec velit ut, ullamcorper bibendum dui. Nulla varius lectus nisi, sit amet posuere arcu porttitor eget. Suspendisse nec malesuada dui. Praesent varius nunc luctus sem interdum eleifend. Ut sed arcu gravida lacus vulputate commodo a nec sapien. Sed at quam rutrum, convallis lorem quis, vulputate nulla. Cras vitae congue turpis. Etiam vehicula lobortis felis, nec rhoncus ligula interdum nec. Curabitur turpis dolor, aliquet at ultrices et, ultrices cursus magna.";
function splitString(str){
if(str.length>=30){
let aux = str.split(" ");
let printString = "";
while(printString.length + aux[0].length + 1 <=30){
printString += (aux.shift() + " ");
}
console.log(printString);
splitString(aux.join(' '));
}
else{
console.log(str);
}
}
splitString(str);

最佳答案

您只需要一个正则表达式,它返回一个包含拆分短语的数组。

@Nick 在这里回答的荣誉:
Split string at space after certain number of characters in Javascript

 let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet ligula arcu, ut ullamcorper lacus porttitor in. Nulla consequat viverra cursus. Curabitur sit amet libero nec velit sagittis vulputate sit amet vel lorem. Nam consectetur quam est, non semper ipsum porttitor et. Pellentesque tempor eros eget urna efficitur, nec malesuada ipsum laoreet. Curabitur dictum eros quis semper ultrices. Aliquam nisl ante, sodales nec velit ut, ullamcorper bibendum dui. Nulla varius lectus nisi, sit amet posuere arcu porttitor eget. Suspendisse nec malesuada dui. Praesent varius nunc luctus sem interdum eleifend. Ut sed arcu gravida lacus vulputate commodo a nec sapien. Sed at quam rutrum, convallis lorem quis, vulputate nulla. Cras vitae congue turpis. Etiam vehicula lobortis felis, nec rhoncus ligula interdum nec. Curabitur turpis dolor, aliquet at ultrices et, ultrices cursus magna.";

console.log( str.match(/.{1,29}(\s|$)/g) );

关于javascript - 使用最大字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250398/

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