字符串示例是这样的 "这是一个很长的句子,我需要分成5行,但不管我怎么努力,我似乎无法让它在我的网站上工作我需要帮助,谢谢你"
1行 - 每行最多50个字符
"这是一个很长的句子,我需要打破"
2行 - 每行最多50个字符
"分为5行,但无论我怎么努力,我都会#34;
3行 - 每行最多50个字符
"似乎无法在网站I"
上工作4行 - 每行最多50个字符
"需要帮助,谢谢你"
5行 - 最多50个字符,但是当它击中完成字符串时它是空白的。
=============
这是我现在的脚本
var string = "spand span spand span";
var arr = string.split(" ");
var unique = [];
var arrcount = [];
$.each(arr, function (index,word) {
if ($.inArray(word, unique) === -1)
unique.push(word);
arrcount.push(word.split(" ").length);
});
alert(unique+arrcount);
====== 我似乎无法计算如何能够计算单词的总字符串并在字符串仅按单词达到50个字符后打破字符串,并且不想按字符分解单词。
我找到了我要找的东西:)
function splitLine(st,n)
{var b = ''; var s = st;while (s.length > n) {var c = s.substring(0,n);var d = c.lastIndexOf(' ');var e =c.lastIndexOf('\n');if (e != -1) d = e; if (d == -1) d = n; b += c.substring(0,d) + '\n';s = s.substring(d+1);}return b+s;}
var myText="This is a long sentence that I need to break into 5 lines but no matter how hard I try I cannot seem to get it to work on my website I need help thank you";
var myText40 = splitLine(myText,50);
var myHTML = myText40.replace(/\n/g,'<br \/><br \/>');
答案 0 :(得分:2)
这会将字符串拆分为每行最多50个字符的行。如果您确实需要5行,则应使用较小的限制 - 您可以使用maxlen = string.length/5
来获得均匀的点差。
var rows = [];
var maxlen = 50;
var arr = string.split(" ");
var currow = arr[0];
var rowlen = currow.length;
for (var i = 1; i < arr.length; i++) {
var word = arr[i];
rowlen += word.length + 1;
if (rowlen <= maxlen) {
currow += " " + word;
} else {
rows.push(currow);
currow = word;
rowlen = word.length;
}
}
rows.push(currow);
给定输入字符串,它返回:
["This is a long sentence that I need to break into", // 49 characters
"5 lines but no matter how hard I try I cannot seem", // 50 characters
"to get it to work on my website I need help thank", // 49 characters
"you"] // 3 characters
答案 1 :(得分:0)
试试这个:
<div id="dv">This is a long sentence that I need to break into 5 lines but no matter how hard I try I cannot seem to get it to work on my website I need help thank you</div>
var text = $("#dv").html();
var newtext = text.match(/.{1,44}/g).join("<br/>");
$("#dv").html(newtext);
<强> DEMO 强>
注意我在 44 字词之后添加了<br/>
来实现您在质疑中提到的文字。让他们 50 会在不同位置添加<br/>
。我猜你没有算spaces
。
答案 2 :(得分:-1)
找到我想要的东西感谢大家的帮助
function splitLine(st,n)
{var b = ''; var s = st;while (s.length > n) {var c = s.substring(0,n);var d = c.lastIndexOf(' ');var e =c.lastIndexOf('\n');if (e != -1) d = e; if (d == -1) d = n; b += c.substring(0,d) + '\n';s = s.substring(d+1);}return b+s;}
var myText="This is a long sentence that I need to break into 5 lines but no matter how hard I try I cannot seem to get it to work on my website I need help thank you";
var myText40 = splitLine(myText,50);
var myHTML = myText40.replace(/\n/g,'<br \/><br \/>');