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>
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:
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:
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.