我有一个字符串
var string = "mario rossi laureato";
我只有15个字符可用于写入表格。
所以预期的结果应该是这样的:
<td id="firstTD">mario rossi</td> //this td has 15 characters available
<td id="secondTD">laureato</td>
第十五位与“laureato”这个词相交,所以它计算了多余的,并取了前一个词。
另一个例子:
var string2 = "hello my name is Paolo"
所以预期的结果应该是这样的:
<td id="firstTD">hello my name</td> //this td has 15 characters available
<td id="secondTD">is Paolo</td>
第十五位与单词“is”相交,所以它计算了多余的,并取了前一个单词。
伙计们对此有何想法?
答案 0 :(得分:0)
var str = "mario rossi laureato";
var strArr = str.match(/.{1,15}/g);
console.log(strArr.length);
for(var s=0,slen=strArr.length; s < slen; s++) {
console.log(strArr[s]);
//create td and append or append strArr[s] to existing td
}
答案 1 :(得分:0)
试试这个:http://jsfiddle.net/Zh8RR/
// Sample string, to make it easy to see the cut points I've use 1-15 in hex to give us a nice easy way to see the breaks
var string = "1234567 9ABCDE 12345 7 89AB 123456 89ABC E 12 45 789A CD 123";
// Break input string up into words
var parts = string.split(' ');
var sections = [""];
var rows = 0;
// For each word
for (var i = 0; i < parts.length; ++i) {
// If it makes the section too long push it to the next section:
if (sections[rows].length + parts[i].length + 1 > 15) {
rows++;
}
// If we have no text initialise it to be the current word
if(!sections[rows]) {
sections[rows] = parts[i];
} else {
// Otherwise use a space as a separator and concat them.
sections[rows] += " " + parts[i];
}
}
// Write them out to a sample div so we can check.
$('div').html(sections.join("<br />"));