Reputation: 21
I have been given a task... "count the number of words in the string "tx_val" that have 3,4,5 or 6 characters show these four counts on a single line separated by commas"
I have been trying multiple different loop statements but I cannot seem to get the right answer.
Here is the code I was given to work with :
<html>
<head>
<script language="javascript">
<!--
function fred()
{
var tx_val=document.alice.tx.value;
len_tx=tx_val.length
-->
</script>
</head>
<body>
<form name="alice">
<b>Assignment #1 Javascript</b>
<p>
The text box below is named "tx". The form is named "alice".
<p>
<input type="text" name="tx" formname="alice" size="50" value="the quick brown fox jumped over the lazy dogs back">
</form>
Upvotes: 1
Views: 929
Reputation: 3728
I don't know Javascript. But your code should go like this:
function fred()
{
var threeCharacterLong = 0;
var fourCharacterLong = 0;
var fiveCharacterLong = 0;
var sixCharacterLong = 0
var tx_val=document.alice.tx.value;
var splittedArray = tx_val.Split(" ");
foreach (var word in splittedArray)
{
if (word.length == 3)
threeCharacterLong++;
else if (word.length == 4)
fourCharacterLong ++;
else if (word.length == 5)
fiveCharacterLong ++;
else if (word.length == 6)
sixCharacterLong ++;
}
}
Upvotes: 0
Reputation: 413737
The regular expression /\b\w{3,6}\b/
matches a "word" of 3 through 6 characters in length. Now that definition of "word" may or may not suit your purposes, but it's probably close.
With that, you could do something like:
var matches = theString.match(/\b\w{3,6}\b/g).length;
to get the count.
The escape "\w" matches any "word" character, which to JavaScript means alphanumerics and underscore. If you don't like that, you could construct your own character class. For example, if you only care about words made up of letters, you could do:
var matches = theString.match(/\b[a-zA-Z]{3,6}\b/g).length;
The "\b" escape is a zero-length match for a word delineation. It matches either the start or the end of a word, without itself "consuming" any characters while doing so.
edit — sorry I had originally mistyped a "." in the {3,6}
qualifier (and I almost did it again just now :-) — should have been commas.
Upvotes: 4
Reputation: 303254
Here are some simple questions that might help you build up a straightforward approach:
if
statement?That said, here's how I personally would do it (which probably would not satisfy your homework requirements if you copy/pasted it without understanding it):
var text = "Oh HAI, is this the longest text allowd?"
for (var counts=[],l=3;l<=6;++l){
var re = new RegExp('\\b\\w{'+l+'}\\b','g');
var words = text.match(re);
counts.push(words ? words.length : 0);
}
console.log(counts.join(','));
//-> 2,2,0,1
Upvotes: 0
Reputation: 129001
You can first split the words into an array using the split
method. Then you can loop over that array using its forEach
method and counting the length of each word.
Upvotes: 1