PDA

View Full Version : JavaScript - limit title characters?


WoodiE
02-12-2009, 02:28 PM
I'm using the following code to display the latest threads in my footer, however I'd like to limit the number of characters that are shown in the Thread title.

Can anyone show me what needs to be changed to say limit it to the first 20 or so characters?


<script type="text/javascript" src="http://www.mydomain.com/external.php?type=js"></script>
<script type="text/javascript">
<!--
for (var i = 0; i < threads.length; i++)
{
document.write('<li><a href="http://www.mydomain.com/showthread.php?t=' + threads[i]['threadid'] + '" title="' + threads[i]['title'] + '">' + threads[i]['title'] + '</a></li>');
}
//-->
</script>



Thanks!

TigerC10
02-13-2009, 11:00 PM
You're looking for substring.


<script type="text/javascript" src="http://www.mydomain.com/external.php?type=js"></script>
<script type="text/javascript">
<!--
for (var i = 0; i < threads.length; i++)
{
document.write('<li><a href="http://www.mydomain.com/showthread.php?t=' + threads[i]['threadid'] + '" title="' + threads[i]['title'] + '">' + threads[i]['title'].substr(0, 20) + '</a></li>');
}
//-->
</script>


But that won't look very pretty (normally people expect things that are cut off to end with ellipsis (http://en.wikipedia.org/wiki/Ellipsis)), I would recommend splitting it up like so...


<script type="text/javascript" src="http://www.mydomain.com/external.php?type=js"></script>
<script type="text/javascript">
<!--
for (var i = 0; i < threads.length; i++)
{
var url = '<li><a href="http://www.mydomain.com/showthread.php?t=' + threads[i]['threadid'] + '" title="' + threads[i]['title'] + '">';

if(threads[i]['title'].length > 20) {
url += threads[i]['title'].substr(0, 20) + '...';
}
else {
url += threads[i]['title'];
}
url += '</a></li>';
document.write(url);
}
//-->
</script>


That way you get the ellipsis at the end of thread titles that are cut off.