javascript – JS:将长字符串拆分为具有char限制的字符串,同时避免拆分单词
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – JS:将长字符串拆分为具有char限制的字符串,同时避免拆分单词,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1923字,纯文字阅读大概需要3分钟。
内容图文
![javascript – JS:将长字符串拆分为具有char限制的字符串,同时避免拆分单词](/upload/InfoBanner/zyjiaocheng/700/8411cbf9d4624b338111b838ee1bafd1.jpg)
我正在尝试将大块文本分成多个字符串,每个字符串为148个字符,同时避免切断单词.
我现在有这个,这是分裂的话:
var length = shortData.new.length;
if (length < 160){
outputString[0] = shortData.new;
document.write(outputString[0]);
}
if (length > 160 && length < 308){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]);
}
if (length > 308 && length < 468){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]);
}
if (length > 468 && length < 641){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,468);
outputString[3] = shortData.new.substring(468,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]+"(txt4more..)");
document.write(outputString[3]);
}
解决方法:
您可以使用此函数,只需传入您的字符串和长度,它将返回数组,如:
var outputString = splitter(shortData['new'], 148);
功能:
function splitter(str, l){
var strs = [];
while(str.length > l){
var pos = str.substring(0, l).lastIndexOf(' ');
pos = pos <= 0 ? l : pos;
strs.push(str.substring(0, pos));
var i = str.indexOf(' ', pos)+1;
if(i < pos || i > pos+l)
i = pos;
str = str.substring(i);
}
strs.push(str);
return strs;
}
用法示例:
splitter("This is a string with several characters.120 to be precise I want to split it into substrings of length twenty or less.", 20);
输出:
["This is a string","with several","characters. 120 to",
"be precise I want","to split it into","substrings of",
"length twenty or","less."]
内容总结
以上是互联网集市为您收集整理的javascript – JS:将长字符串拆分为具有char限制的字符串,同时避免拆分单词全部内容,希望文章能够帮你解决javascript – JS:将长字符串拆分为具有char限制的字符串,同时避免拆分单词所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。