2014-06-09 21 views
0

我有一个字符串分裂有可能的最大字符数字的字符串在TD

var string = "mario rossi laureato"; 

,我有可以在表的TD只写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> 

第十五位相交的词“是”,那么它的计算多余的,并采取了一个字。

伙计们对此有何想法?

+1

有人问如何在PHP中做到这一点,但我提供了一个[CSS-只(HTTP://计算器。 com/questions/11434091/add-if-string-is-too-long-php/11434149#11434149)解决方案对他们来说效果很好。主要原因在于,考虑“lllllllllllllll”和“WWWWWWWWWWWWWWW”之间的大小差异 –

+0

可能将字符串拆分为空格,循环直到字长+字数-1超过15,然后将该点之前的所有内容都作为字符串1 ? – scragar

+0

@所有答案在下面,请仔细阅读问题,他希望确保他不会分裂词语,如果你使用的是不恰当的语言,你的答案是错误的! – scragar

回答

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 />")); 
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 
} 
+0

检查这个小提琴不会是一个更好的解决方案吗? http://jsfiddle.net/x5jRa/ –