restrict string length to nearest word

They have: 426 posts

Joined: Feb 2005

OK so I have been looking and asking around the interest for months now because I cant figure out how to restrict a length of a string to the nearest word?

Bsically, I do this: str.substr(0,20) which may result in: "This is a wor..." when it should be "This is a word...."

How can I do this?

I tried using lastIndexOf() with no luck.

Vincent Puglia's picture

They have: 634 posts

Joined: Dec 1999

Hi,

Is this what you're looking for?

[code]

function doIt(str)
{
var x = 0
do {
x = str.lastIndexOf(" ");
alert(x);
if (x > 20)
str = str.substr(0,x);
} while (x > 20)
alert(str.substr(0,x))
}

[/code]

Where the world once stood
the blades of grass cut me still

They have: 426 posts

Joined: Feb 2005

Hi Mate,

This doesnt work?

Something similar to wordwrap in PHP?

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

You could break it up into an array.

<?php
$words
= explode(' ', $text);
?>

The work with it accordingly, and implode() it when done. I'm not sure how well that will scale, but it should work.

They have: 426 posts

Joined: Feb 2005

Hi Mate,

I need this in Javascript?

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

Woops, my bad.

They have: 1 posts

Joined: Feb 2010

Something similar to wordwrap in PHP?

{links removed}

They have: 426 posts

Joined: Feb 2005

OK I finally cracked by finding "charAt()".

Here it is:

           var s = 'This is a string and it is more than 10 chars long';
           var max = 29;
           if(s.charAt(max) != ' '){
             var t = 1;
             while(s.charAt((max + t)) != ' '){
               t++
             }
             document.write(s.substr(0,(max + t)));
             document.write('<br />'+s)
           }

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.