473,654 Members | 3,097 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

working word counter

After getting some help working through my bugs, I have what seems to
be a robust, working word counter script. I post it here to benefit
others that might want this in the future and so that if I ever lose
my copy I can come back here to find it :) Some other scripts that I
used for inspiration failed when confronted with whitespace before the
string or miscalculated when encountering linefeeds and other
non-space spaces, so I made mine better. Definition of words for this
exercise is contiguous groups of characters separated by whitespace.
Maybe it will even be useful to somebody besides me.

Cheers!
--David

<html>
<!--Generated 02/12/04-->
<!--modified 02/15/04-->
<!--name of this file: "wordCounter.ht ml" -->

<head>
<title>Word Counter</title>
<SCRIPT LANGUAGE="JavaS cript">

function trim(data)
{
while (/\s/.test(data.char At(0)))
{data=data.subs tring(1,data.le ngth);}
while (/\s/.test(data.char At(data.length-1)))
{data=data.subs tring(0,(data.l ength-1));}
return data;
}

function countWords()
{
var input, wordList, output;
input=document. forms[0].elements[0].value;
input=trim(inpu t);
wordList=input. split(/\s+/g);
output=wordList .length;
document.forms[0].elements[0].focus();
return output;
}

</SCRIPT>
</head>

<body bgcolor="#66666 6"
text="#00ff00"
link="#ffffcc"
vlink="#ffffcc" >

Enter or paste text into the box below and press <b>count</b> to see
the total number of words.
<br>
<br>
<form onSubmit="retur n false">
<center>
<textarea rows="30" cols="100"></textarea>
<br>
<br>
<button onClick="alert( 'total words = ' + countWords())"
class="button"> count</button>
</center>
</form>

</body>
</html>
Jul 20 '05 #1
2 1596
David wrote:
After getting some help working through my bugs, I have what seems to
be a robust, working word counter script. I post it here to benefit
others that might want this in the future and so that if I ever lose
my copy I can come back here to find it :) Some other scripts that I
used for inspiration failed when confronted with whitespace before the
string or miscalculated when encountering linefeeds and other
non-space spaces, so I made mine better. Definition of words for this
exercise is contiguous groups of characters separated by whitespace.
Maybe it will even be useful to somebody besides me.

Cheers!
--David

function trim(data)
{
while (/\s/.test(data.char At(0)))
{data=data.subs tring(1,data.le ngth);}
while (/\s/.test(data.char At(data.length-1)))
{data=data.subs tring(0,(data.l ength-1));}
return data;
}
trim() would be better implemented as:

String.prototyp e.LTrim = new Function("retur n this.replace(/^\\s+/,'')")
String.prototyp e.RTrim = new Function("retur n this.replace(/\\s+$/,'')")
String.prototyp e.Trim = new Function("retur n
this.replace(/^\\s+|\\s+$/g,'')")

as shown in the FAQ at <url: http://jibbering.com/faq/#FAQ4_16 />
function countWords()
{
var input, wordList, output;
input=document. forms[0].elements[0].value;
input=trim(inpu t);


Using the Trim() method outlined above, this would become:

input = input.Trim();

--
| Grant Wagner <gw*****@agrico reunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp

* Netscape 6/7 DOM Reference available at:
* http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
* http://www.mozilla.org/docs/web-deve...upgrade_2.html
Jul 20 '05 #2
JRS: In article <67************ **************@ posting.google. com>, seen
in news:comp.lang. javascript, David <da***********@ mindspring.com>
posted at Sun, 15 Feb 2004 23:51:19 :-
After getting some help working through my bugs, I have what seems to
be a robust, working word counter script. <!--Generated 02/12/04-->
this is an international newsgroup; please use internationally-
comprehensible notation. The above, in most countries, is 2nd December
2004. The correct form is 2004-02-12; or put the month as Feb and use
YYYY.
input=trim(inp ut);
wordList=input .split(/\s+/g);
output=wordLis t.length;


What purpose does trim serve here? and /g?

I find
Q = X.replace(/\S+/g, 'a').replace(/\s+/g, '').length
to be significantly faster than
Q = X.split(/\s+/).length
for strings with many words. The latter creates many Objects.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5994
by: Eric A. Johnson | last post by:
Hi, Thanks for reading this. How do I list all possible permutations of a word? I've figured out how to get all the characters in alphabetical order. I then want to display every possible character permutation in sequence, like so: abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba This is turning out to be much more difficult than I thought it would be. It seems to...
2
2215
by: Anouar | last post by:
The point was to make a program that gives you the possibilty to enter a sentence and when you press "enter" it should ask a number for example when i press 4 It should take the 4th word out of the sentence and print it example sentence "hello i am Anouar" the space after hello should not be a problem for the program so whe i ask for the second word it should give "i" for an answer.. this is what i've got so far
0
754
by: John | last post by:
My application needs to capture the text the user has typed on a word document. I have control of the Word application/document with the following code: Word.Application word = Marshal.GetActiveObject ("Word.Application"); doc = word.ActiveDocument; How do I get the Text that the user has typed?
0
1442
by: hinew | last post by:
Hi. I have created macro for Microsoft word. However I need this to be run in visual baisc application. I need a program that ask user to select the word document which need to be processed. And after selecting the document and by clicking 'proceed', the program will automatically open the word document up and procede the macro. Can anyone help me please?
7
2014
by: onetitfemme | last post by:
Hi, for some reason Firefox is apparently inserting a new line somehow after some IPA symbols which I have written in their hexadecimal notation. Also, I would like to have two spaces by default in textual fields from tables. What would be the style sheet statements to achieve this?
10
2069
by: Antoine De Groote | last post by:
Hi there, I have a word document containing pictures and text. This documents holds several 'ABCDEF' strings which serve as a placeholder for names. Now I want to replace these occurences with names in a list (members). I open both input and output file in binary mode and do the transformation. However, I can't open the resulting file, Word just telling that there was an error. Does anybody what I am doing wrong? Oh, and is this...
10
5221
by: Stephen.Schoenberger | last post by:
Hello, Sorry if this is not "exactly" a C topic but I thought this would be the best place to start. I need some guidance on working with bitmap images in ANSI C. I need to "read" in a bitmap image, then break it up into pieces (say 32x32) then take those pieces and "save" them, granted they do not need to be a readable image, then perform some other operations on the pieces, and then combine the manipulated pieces back into one image.
6
3375
by: boyindie86 | last post by:
Hi I have been fighting with this lump of code for the last week what I am trying to do is that I am passing words into passages of texts, and I want the system to go and find exact word matches only and place square brackets around them e.g word = car PASSAGE: the red car required a lot of care to prevent a scar I only want it to place a square bracket around the word car and ignore the car in "Care" and "scar"
3
3651
by: dirknrw | last post by:
Hi, I have a tricky question!? :-) I'm using the perl -e command in order to match lines between two search patterns. The problem I have is, for the first example it is working, for the second not, but I can't see the difference: 1) ok: sharan:~/tmp/koala/nokkcc (171) % perl -ne 'print if /M1000C0/ .. /<\/Counter>/' nokrwwKOALA.xml <Counter ID="ave_prxtot_class_0" OMeSName="M1000C0" NEName="AVE PRXTOT CLASS 0">
0
8290
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8593
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7306
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5622
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2714
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.