# Truncating long words with javascript - need help adjusting code

**URL:** https://forum.kirupa.com/t/truncating-long-words-with-javascript-need-help-adjusting-code/69474
**Category:** web dev
**Created:** [November 4, 2004, 5:24pm UTC](https://forum.kirupa.com/t/truncating-long-words-with-javascript-need-help-adjusting-code/69474 "2004-11-04T17:24:40Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![plastikaa](https://avatars.discourse-cdn.com/v4/letter/p/b5e925/32.png) [@plastikaa](https://forum.kirupa.com/u/plastikaa)
#### Post date: [November 4, 2004, 5:24pm UTC](https://forum.kirupa.com/t/truncating-long-words-with-javascript-need-help-adjusting-code/69474/1 "2004-11-04T17:24:40Z")

</div>

At the moment I’m using the following code to truncate words that are over 15 characters long, and add ‘…’ onto the end to show the word has been truncated - im using this on part of a forum where users post the words so I have no control over the length of the word but need to make sure the layout of the page doesnt mess up.

Placed inbetween head tags

```auto

<script language="javascript" type="text/javascript">
<!--
var mxw_max = 5;
function mxw(id)
{
  if (!document.getElementById) return;
  var n = document.getElementById(id);
  if (!n || !n.nodeType) return;
  mxw2(n);
}
function mxw2(n)
{
  if (n.nodeType == 3 /*Node.TEXT_NODE*/)
  {
	var flag = 0;
	  var words = n.data.split(" ");
	for (var i = 0; i < words.length; i++)
	{
	  if (words*.length > mxw_max)
	  {
		flag++;
		words* = words*.substr(0, mxw_max-2) + "... "; 
	  }
	}
	if (flag > 0) n.data = words.join(" ");
  }
  var children = n.childNodes;
  for (var i = 0; i < children.length; i++) mxw2(children*); 
}
//-->
</script>

```

Then on the page I use the following around the user posted text to truncate the word.

```auto

<div id="shorten">Userpostedtextishere</div><script language="javascript" type="text/javascript">mxw("shorten");</script>

```

So ‘Userpostedtextishere’ would become ‘Userpostedtex…’

The problem is that I can only use this on one part of the page - unless i give different ID’s to all the divs on every part of the page where I need to use it.

How can I get this to work so I can use the same div and script around the words on every part of the page?

(BTW: Im know nothing much about javascript as I’m just a html person - so please dont just tell me the changes to the header code I must make as I probably wont understand)

All help will be appreciated a lot!

Thanks,
