gpt4 book ai didi

javascript - 在 String 中每 100 个字符以最近的间距添加一个新行

转载 作者:行者123 更新时间:2023-11-28 05:06:41 24 4
gpt4 key购买 nike

我正在为我的冰淇淋制造公司编写生产系统的后端代码,自从大学一年级以来我就没有使用过 Javascript。基本上,myString 是从我们的订购系统导入的 Google Sheet 中的成分列表。它通常很长,需要被分割以供标签软件使用。我需要将所有 myString 保留在一个单元格中,但每 100 个字符就有一个新行(或 CTRL Enter),但它必须位于一个空格处。这是我所拥有的,但它在第一次出现后不起作用。

function insertNewLine(myString) {
var ret = [];
var i;
var len;
var n = 100;
var currentString = myString.substr(i,n);
var character = String.fromCharCode(10);

for(i = 0, len = myString.length; i < len; i += 100) {

var before = currentString.lastIndexOf(' ', n);
n = before;

ret.push(currentString + character);
currentString = myString.substr(n, n+100);
n=100;
}

return ret;
}

感谢您的帮助。

最佳答案

首先拆分为单词数组并迭代该数组以构建新字符串的方法

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

var lineBreak = '\n',
words = str.split(' '),
newStr = words.shift(),
charCount = newStr.length;

words.forEach(function(word, i) {
charCount += word.length + 1;
if (charCount <= 100) {
newStr += ' ';
} else {
newStr += lineBreak;
charCount = word.length
}
newStr += word;
});
// demo only to show line lengths
var lines= newStr.split(lineBreak).map(function(str){
return str.length
})
document.getElementById('res').value = newStr;
document.getElementById('lengths').innerHTML = JSON.stringify(lines);
<h3>line lengths</h3>
<pre id="lengths"></pre>
<h4>new Text</h4>
<textarea id="res" style="width:100%; height:300px"></textarea>

关于javascript - 在 String 中每 100 个字符以最近的间距添加一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41688949/

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