restrict string length to nearest word
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 posted this at 02:49 — 18th February 2010.
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
benf posted this at 15:42 — 22nd February 2010.
They have: 426 posts
Joined: Feb 2005
Hi Mate,
This doesnt work?
Something similar to wordwrap in PHP?
pr0gr4mm3r posted this at 16:39 — 22nd February 2010.
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.
benf posted this at 17:08 — 22nd February 2010.
They have: 426 posts
Joined: Feb 2005
Hi Mate,
I need this in Javascript?
pr0gr4mm3r posted this at 21:46 — 22nd February 2010.
He has: 1,502 posts
Joined: Sep 2006
Woops, my bad.
aion4217 posted this at 08:46 — 23rd February 2010.
They have: 1 posts
Joined: Feb 2010
Something similar to wordwrap in PHP?
{links removed}
benf posted this at 12:18 — 23rd February 2010.
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)
}
Good Value Professional VPS Hosting
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.