Jump to content

Word count


Recommended Posts

I have looked SEVERAL places trying to come up with a JavaScript that will counts words in a field and use the result to try and make a better appearing line break.


In every instance, I find a way to populate a web-based form and count the words in it. So far, I've been unsuccessful in "converting" that to my Variable Print document.


Basically, I have a field that has from 3 to 10 "words" (Company Name) and have to add that to 4 more words to create a headline on a newspaper as a variable element. I'm combining all of this with a Copyfit rule. Needless to say, it's making some ugly decisions, so, I thought I'd try and count the total number of words in the Fieldname and static part that are inserted into a string (var), count the words, and apply some linebreak logic..


Word Counting Function I have started with is:


function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}

Any idea where I can insert my variable/string into this function to get a word count and then if I end up with 20 words, go 10 words into the variable and add a linebreak?


Thanks for any help anyone can offer...

Link to comment
Share on other sites

  • 2 weeks later...

Does something like this example help?


[size=2]var companyname = "This is a sample Company name"; // put field name here instead of raw text
var fulltext = companyname + " plus the added text for headline";
fulltext_array = fulltext.split(" ");
newtext ="";
for (x=0; x < fulltext_array.length; x++){
if (x == 9){
newtext = newtext + fulltext_array[x] + "\n";
else if (x == fulltext_array.length){
newtext = newtext + fulltext_array[x];
else {
newtext = newtext + fulltext_array[x] + " ";
return newtext;

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...