0

I have a string

var string = "mario rossi laureato";

and I have only 15 characters available to write in a td of a table.

so the expected results should be this:

<td id="firstTD">mario rossi</td> //this td has 15 characters available
<td id="secondTD">laureato</td>

fifteenth place intersects the word "laureato", so it's calculated the excess , and takes the previous word.

another example:

var string2 = "hello my name is Paolo"

so the expected results should be this:

<td id="firstTD">hello my name</td> //this td has 15 characters available
<td id="secondTD">is Paolo</td>

fifteenth place intersects the word "is", so it's calculated the excess , and takes the previous word.

Guys any idea about this?

olly_uk
  • 11,559
  • 3
  • 39
  • 45
  • 1
    Someone asked how to do this in PHP, but I offered a [CSS-only](http://stackoverflow.com/questions/11434091/add-if-string-is-too-long-php/11434149#11434149) solution that worked well for them. Main reason being, consider the difference in size between "lllllllllllllll" and "WWWWWWWWWWWWWWW" – Niet the Dark Absol Jun 09 '14 at 10:54
  • Maybe splitting the string on spaces, the looping until the length + num of words - 1 is more than 15, then taking everything before that point as string 1? – scragar Jun 09 '14 at 10:55
  • @All the answers below, PLEASE READ THE QUESTION, HE WANTS TO ENSURE HE DOESN'T SPLIT WORDS, IF YOU ARE USING AN INDISCRIMINATE SUBSTRING YOUR ANSWER IS WRONG! – scragar Jun 09 '14 at 11:49

2 Answers2

0

you could do:

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
} 
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

Try this: 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 />"));
scragar
  • 6,764
  • 28
  • 36