...

View Full Version : How can I truncate all words greater than 30 characters when page loads?



Terran
12-23-2010, 07:17 PM
How can I truncate all words greater than 30 characters using a class name when the page loads?

Been trying to do this for about 5 hours. Trying to conside the following:

* Truncate long words and churn anything above the minimum length with an ellipse.
* Only truncate words and not the whole sentence or paragraph.
* Should truncate text that are inside HTML tags and not truncate the tags themselves.
* When you hover over the ellipse, it will show you the complete word.
* The long words are already truncated when the page load (SEO friendly).
* Block of text are included in a max of 25 <div> elements and a minimum of 1. That's why I'm not using ID.

So far I have this lines of code:



<script charset="utf-8" language="javascript" type="text/javascript">
function test(gaz) {
var sbText = gaz.innerHTML;
var sbTextArr = sbText.split(' ');
var tempText = "";
for (var s=0; s<sbTextArr.length; s++) {
if (sbTextArr[s].length > 30) { sbTextArr[s] = "marco"; }
gaz.innerHTML = "";
tempText = tempText + " " + sbTextArr[s];
gaz.innerHTML = tempText;
}
}</script>

<div class="myClass" onmouseover="test(this);"><p>This is a <strong>looooooooooooooo</strong><em>ooooooooooooooooooooooooooooooong</em> word.</p></div>
<div class="myClass" onmouseover="test(this);">A text without long word.</div>
<div class="anotherClass"><p>Another set</p><p>But should not affect if there's a loooooooooooooooooong word.</p></div>


I got this from the web and modified it but not working as I intended it to be.

Useful for posts in forums, blog comments, and guestbooks

Philip M
12-23-2010, 07:51 PM
I do not see the point of trying to truncate words of more than 30 characters. The longest English word is supposed to be antidisestablishmentarianism - 26 letters. It would be very difficult to truncate any text with mark-up in it as you have. Why not simply truncate the whole text at a certain number of characters?


Example:-


<body onload = "showstart()">
<div id = "mydiv"></div>

<script type = "text/javascript">

var txt = "";
var shorttxt = "";
function showstart() {
txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor. "
shorttxt = txt.substring(0,100);
document.getElementById("mydiv").innerHTML = shorttxt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showmore();return false'>.....read more</a>";
}

function showmore() {
document.getElementById("mydiv").innerHTML = document.getElementById("mydiv").innerHTML = txt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showless();return false'>.....read less</a>";txt;
}

function showless() {
document.getElementById("mydiv").innerHTML = shorttxt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showmore();return false'>.....read more</a>";
}

</script>

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

DJCMBear
12-23-2010, 08:53 PM
Hey Philip just an Idea, would this work?

Strip all the html tags and double spaces so something like this.

<span class="demo">hello world</span>

Would turn into this.

hello world

And then set that string as a variable for usage in the function and then split it up by the spaces and then check the length of each array item, once it finds a word longer than 30 chars it will shorten it and replace the old long word with the new shorten word.

May not work but worth thinking of as it might work. Also do agree with you with shortening the full string with the html tags in it but what if the string gets shorten down and a string like this hello <sup>world</sup> get shorten down and then returns hello <sup>world</s the </s would also be displayed so wouldn't it be best to try and stop this happening.

Philip M
12-23-2010, 09:27 PM
I think it would be very difficult indeed to deal with HTML tags as you suggest. In any case, it see it as another fundamentally flawed idea.

If there are mark-up tags e.g.
txt = "Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam </strong>ipsum leo, scelerisque
then either you count the tags as part of the string length, or you remove them with a regex. I don't see how it is possible to do both.

You could count the characters between HTML tags and add that number to the truncated text - but as I see it it is impossible to detect whether the tags are before or after the revised length (and the truncate cut-off might fall within a tag).


var txt = "";
var shorttxt = "";
function showstart() {
txt = "Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam ipsum leo</strong>, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor. "

var len = txt.length;
alert (len); // 869
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
var trunclen = txt.replace(regexp,"").length;
alert (trunclen); // 852

var x = 100 + (len-trunclen);
shorttxt = txt.substring(0, x);

DJCMBear
12-23-2010, 09:36 PM
Good idea Philip I always find it best to have no tags on a shorten string so like you did was you took them out and when you click read more the full text would be styled then with the strong tag etc.

DJCMBear
12-23-2010, 10:49 PM
A thought just came to me, WHY use javascript for this????

Why not just use css? so much more simple and also keeps the html styles on the text.

EXAMPLE:


<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
.demo {
width: 130px;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
</head>
<body>
<div class="demo">Hello World</div>
<div class="demo">Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam ipsum leo</strong>, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor.</div>
<div class="demo">Hello World Again!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>
</body>
</html>

Philip M
12-24-2010, 07:37 AM
All codes written by me have been 100% tested.


Not this one! :)

DJCMBear
12-24-2010, 02:06 PM
Not this one! :)


Well it works on my website so it must be your server/computer.

Also try adding white-space: no-wrap; to the demo class CSS this will stop the text from wrapping to a new line.

Philip M
12-24-2010, 04:10 PM
Well, what I get in IE8 is

Hello World
Lorem ipsum dolor
sit amet,
consectetur
adipiscing elit.
Etiam ipsum leo,
scelerisque at
dapibus ac,
consectetur vel
ipsum. Morbi et
metus ut diam
molestie
//.......
Hello World
Again!!!!!!!!!!!!!!!...

DJCMBear
12-24-2010, 04:16 PM
C'mon IE messes up on everything lol!!

Terran
12-26-2010, 06:25 PM
I do not see the point of trying to truncate words of more than 30 characters. The longest English word is supposed to be antidisestablishmentarianism - 26 letters. It would be very difficult to truncate any text with mark-up in it as you have. Why not simply truncate the whole text at a certain number of characters?

Okay, then maybe 25. I want to truncate words because some people add lengthy characters creating horizontal scrollbar to appear and messing up the pages. Such are these examples:

I loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooveeeeeeeeeeeeeeeeeeeeeeeeeeeeeee eeee Emma Watson!
Shut Up!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!
Or sometimes forgot to addspacestowordsandcopyandpastedthemwrongcreatinglongcharacters.
Or when a period comesafteralong.wordsuchasthiscreatinghorizontalbarstoappear.
Or when they post long URLs such as http://www.codingforums.com/newreply.php?do=newreply&p=1031430 (but they can be remedied easily so the lengthy words are more of my concern).


EDIT: I'm new here so I'm not sure why. Tried clicking "Thank user for this post" but it says I do not have permission to do that. So I just want to add thank you guys for the replies. I think I'm going to like this message board.

rnd me
12-26-2010, 10:32 PM
here's a slightly more educated way of doing a truncation, keeping in mind that 30 "I"s don't take up as much room as 30 "W"s:

feel free to integrate it into your own scripts.





function slicePix(s,w){ //slices text by visual width in pixels instead of by character counts.
var charWidths={a:10,b:11,c:10,d:11,e:11,f:6,g:11,h:10,i:4,j:4,k:9,l:4,m:16,n:10,o:11,p:11,q:11,r:6,s:10 ,t:5,
u:10,v:9,w:13,x:9,y:9,z:9,A:13,B:13,C:14,D:14,E:13,F:12,G:15,H:13,I:6,J:10,K:13,L:11,M:15,N:13,O:15, P:13,
Q:15,R:14,S:13,T:12,U:13,V:13,W:19,X:13,Y:12,Z:12,0:11,1:11,2:11,3:11,4:11,5:11,6:11,7:11,8:11,9:11} ;

var tot=0, buff = s.split("").filter(function(a,b){
tot+=(charWidths[a]||8);
if(tot<w){return a;}
}).join("");
return buff==s ? s : buff+"...";
}



feed it the string and the approx #of relative pixels. you may have to adjust the pixel allowance for certain fonts, but this function should result in much more consistent visual blocking...

Krupski
12-27-2010, 01:27 AM
C'mon IE messes up on everything lol!!


That's why most web developers call it "IFE" (and you know what the "F" is for)... :)

Krupski
12-27-2010, 01:40 AM
How can I truncate all words greater than 30 characters using a class name when the page loads?


Could this be what you need?



<html>
<head>

<script type="text/javascript">
function truncate(text)
{
if (text.length > 30)
{
var head = text.substring(0, 10);
var tail = text.substring(text.length-10);
text = head + '...' + tail;
}
return text;
}
</script>
</head>
<body>

<script type="text/javascript">
alert(truncate('Hello'));
alert(truncate('Mary had a little lamb, it\'s fleece was white as snow.'));
</script>

</body>
</html>
Output of first "alert": 'Hello'
Output of second "alert": 'Mary had a...e as snow.'

Hope this helps...

-- Roger

(edit to add): To truncate long words in a certain class, maybe you could use "getElementsByClassName" then get their innerHTML, truncate each word then write it back with innerHTML=text?

Note Internet @!^%$# Explorer doesn't support "getElementsByClassName", but there is a nice function that provides it: LINK (http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/)

Instead of doing something like var e = document.getElementsByClassName('class') you simply do var e = getElementsByClassName('class'). Works like a charm.

DJCMBear
12-27-2010, 02:17 AM
That's why most web developers call it "IFE" (and you know what the "F" is for)... :)

That made me laugh, I have no idea why Microsoft is still creating new IE's as even the latest versions (IE8 and IE9) are both really bad I do have to give credit to them though as even though IE7 is still bad it is the best IE browser they have ever made it went from IE6(:eek:) lol IE7(:thumbsup:) IE8+(WTF).

Philip M
12-27-2010, 10:24 AM
To eleminate consecutive letters which are the same:-


<script type = "text/javascript">

var field = "aaabcdeghjk";
if(/^(.)\1{2,}/i.test(field)) { //string begins with at least 3 identical characters (case insenstive)
alert ("Three in a row at the start of the string!");
field= field.replace(/^(.)\1{2,}/i,"");
alert (field);
}

var field = "zeeeend";
if(/(.)\1{2,}/i.test(field)) { //string contains at least 3 identical characters (case insenstive)
alert ("Three in a row within the string!");
field= field.replace (/(.)\1{2,}/i,"");
alert (field);
}

</script>

Philip M
12-27-2010, 10:39 AM
And count the number of long words:-


<script type = "text/javascript">

var txt = "Lorem ipsum!!!! dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper."
txt = txt.replace(/\s+/g," "); // Replace multiple spaces with one space
var txtArray = [];
txtArray = txt.split(" ");
var validwords = 0
var illegalwords = 0;
var maxlen = 15;

for (var i = 0; i <txtArray.length; i++) {
var len = txtArray[i].length;
if (len <= maxlen) {
validwords ++;
}
else {
illegalwords ++;
}
}

document.write ("There are a total of " + validwords + " words <br>");
document.write("There are " + illegalwords + " illegal words of over 15 characters");
</script>

If desired you could truncate the long words with

txtArray[i] = txtArray[i].substring(0,15);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum