I am working on my college homework. I am having a lot of difficulty with it and getting stuck. My class mates are not helping me and the instructor hasn't responded. I am hoping I might get some help/understanding here. The current assignment I am working on and it is due today is:
Create a page containing a textarea and an “analyze” button. The results area will display the frequency of words of x characters. For example, the text “one two three” contains 2 3-character words and 1 5-character word. An improvement to the original design would be to strip out any extraneous characters that may skew the count.
I am just starting it now, so I will add the code here as I update. I know I won't have a problem with the HTML part, the JavaScript will be my problem. From what I get, I will need to have a function that counts the words and the characters in each word. But it needs to exclude spaces and characters like: ,.';/. I have not run across this code before, so any input on how I should frame the javascript will be helpful. Also it seems he wants me to list how many words have the same characters? am I reading this right?
My code thus far:
<!DOCTYPE html>
<html>
<body>
<textarea id="txtarea">
</textarea>
<input type="button" id="analyze" value="Analyze" onclick="myFunction()" />
<p id="demo"></p>
<p id="wcnt"></p>
<script>
function myFunction() {
var str = document.getElementById("txtarea").value;
var res = str.split(/[\s\/\.;,\-0-9]/);
var n = str.length;
document.getElementById("demo").innerHTML = "There are " + n + " characters in the text area.";
for (var i = 0; i < res.length; i++) {
s = document.getElementById("txtarea").value;
s = s.replace(/(^\s*)|(\s*$)/gi, "");
s = s.replace(/[ ]{2,}/gi, " ");
s = s.replace(/\n /, "\n");
document.getElementById("wcnt").innerHTML = "There are " + s.split(' ').length + " words in the text area.";
}
}
</script>
</body>
</html>
Now I need to figure out how to make it count the characters of each word then output how many words have x amount of characters. Such as 5 words have 4 characters and so on. Any suggestions?
var textarea = document.getElementById("textarea"),
result = {}; // object Literal to hold "word":NumberOfOccurrences
function analyzeFrequency() {
// Match/extract words (accounting for apostrophes)
var words = textarea.value.match(/[\w']+/g); // Array of words
// Loop words Array
for(var i=0; i<words.length; i++) {
var word = words[i];
// Increment if exists OR assign value of 1
result[word] = ++result[word] || 1;
}
console.log( result );
}
analyzeFrequency(); // TODO: Do this on some button click
<textarea id="textarea">
I am working on my college-homework.
Homework I am having a lot of difficulty with it and getting stuck.
My class mates are not helping me and the instructor hasn't responded.
I am hoping I might get some help/understanding here.
</textarea>
Notice how Homework and homework (lowercase) are registered as two different words, I'll leave it to you to fix that - if necessary and implement the analyzeFrequency() trigger on some button click.
Most likely you will have to use JavaScript's split function with regex to define all the characters you do not want to include. Then loop through the resulting array and count the characters in each word.
var words = document.getElementById("words");
var analyze = document.getElementById("analyze");
analyze.addEventListener("click", function(e) {
var str = words.value;
var res = str.split(/[\s\/\.;,\-0-9]/);
for(var i = 0; i < res.length; i++) {
alert(res[i].length);
}
});
<textarea id="words">This is a test of this word counter thing.</textarea>
<br/>
<button id="analyze">
Analyze
</button>
Your instructor does NOT want you to list how may words have the same characters but rather the same number of characters. The basic algorithm:
Assign the value of the text area to a variable.
Convert that string value into an array. In javascript this could be accomplished with the String split method using a regular expression containing a character class.
Iterate over that array examining each element for its length. For each element, increment a counting object's property whose property name is the length of the element.
Iterate over the counting object's property list. Output to the result area each property name and its value.
Related
I am trying to make a simple word counter for a textarea element in Javascript. So far I have tried many methods but everyone fails in something. I searched the web but I only found solutions that use functions or JS commands and syntax that I still don't know. The goal is to count the words in a textarea that contains a maximum of 140 characters. The text can also be on more than one line so I have to consider the new line symbol.
Till now I wrote this:
for (let i = 0; i < text.length; i++) {
if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) {
wc++;
}
else if(text[i]=='\n' && text[i-1]!==' '){
wc++;
}
}
It kind of works but it counts only if after the word I press SPACE. Is there any way to start counting from when the user types just one letter?
EDIT:
I have already tried the .split(" ") method but it doesn't work with the ENTER/RETURN key. My goal is to start counting as soon as the user types a letter.
You can use split along with a regex for whitespace
let words = text.split(/\W/);
wc = words.length;
split breaks your string into an array, it creates a new entry to the array everytime it finds the expression you pass to it.
The regex /\W/ gets whitespaces (' ' and '\n')
So this way it would create an array with every word separated, and then you just need to check the length of the array
Added replace all multiple spaces with single space. Also added check if entered a new line.
document.getElementById("inputField").addEventListener("input", function(e) {
// Get the input text value
var text = this.value;
//replace all multiple spaces with single space
text = text.replace(/\s\s+/g, " ");
// Initialize the word counter
var wc = 0;
// Loop through the text
// and count spaces in it
for (let i = 0; i < text.length; i++) {
if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) {
wc++;
}
else if(text[i]=='\n' && text[i-1]!==' '){
wc++;
}
}
// Display it as output
document.getElementById("show").innerHTML = wc;
})
<textarea id="inputField" rows=10 cols="60">
</textarea>
<br><br>
<p> Word Count:
<span id="show">0</span>
</p>
I have the following example where I am putting a limit on the characters entered in the Textarea:
var tlength = $(this).val().length;
$(this).val($(this).val().substring(0, maxchars));
var tlength = $(this).val().length;
remain = maxchars - parseInt(tlength);
$('#remain').text(remain);
where maxchars is the number of characters. How can I change this example to work with words, so instead of restricting chars, I restrict to a number of words.
http://jsfiddle.net/PzESw/106/
I think you need to change one string of your code to something like this:
$(this).val($(this).val().split(' ').slice(0, maxchars).join(' '));
This code splits text in an array of words (you may need another workflow), removes extra words and joins them back
A simple way would be to converting the full String into array of words.
For example you're having a String as:
var words = "Hi, My name is Afzaal Ahmad Zeeshan.";
var arrayOfWords = words.split(" "); // split at a white space
Now, you'll have an array of words. Loop it using
for (i = 0; i < words.length; i++) {
/* write them all, or limit them in the for loop! */
}
This way, you can write the number of words in the document. Instead of characters!
I have a Textarea box, a textbox and a button. I would like on clicking the button, for the word in the textbox to be checked against words in the textarea and count number of occurrence.
I have tried last 2 days to write a click function to do this but not getting anywhere since not sure what codes or logic follows next. Only managed to read the contents in the textarea but not sure how to get the word in the textbox and search against sentence in textarea.
Please I am a newbie in JQuery so not asking for anyone to write the code but more of a guide if possible. If this question isn't permitted here, I am more than happy to delete it. Thanks
Use string.match() along with processing to ensure the first string is not empty and that there actually is a match. Did the following in jQuery since you seemed interested in using it.
var textVal = $('#textbox').val();
var textArea = $('#textarea').val();
var matching = new RegExp('\\b' + textVal + '\\b','g');
var count = textArea.match(matching);
var result = 0;
if (count !== null) {
result = count.length;
}
http://jsfiddle.net/promiseofcake/t8Lg9/3/
You are looking for string occurrences, so take a look at this thread.
You could do this using match(), as suggested in the comments:
var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
// m.length contains number of matches
But that will also match partial words, like 'fox' in 'foxy'. So another method is to split the input into words and walk over them one by one:
var count = 0;
var words = searchText.split(' ');
for (x in words) {
if (words[x].toLowerCase() == wordMatch) {
count++;
}
}
Take a look at this full example: http://jsfiddle.net/z7vzb/
<input type="text"/>
<textarea>...</textarea>
<button>Get</button>
<div></div>
<script>
$("button").click(function(){
count=$("textarea").text().split($("input[type=text]").val()).length-1;
$("div").html(count);
})
</script>
i am not sure as to why this code is not working, on the website where i found the code it say it should print any letter between capital a to z. i tried the same thing with a number, to print numbers between 0-9 but it does not work.
<!DOCTYPE html>
<html>
<body>
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z]/;
document.write(string.match(str));
</script>
</body>
</html>
EDIT:
updated after clarified question
<script>
var string = "1 2 3 4 8 9 11 15 18 293";
var str = /[0-9]*/g;
var arr = string.match(str);
var length = arr.length;
for (var i = 0; i < length; i++) {
if ( parseInt(arr[i]) <= 9 && parseInt(arr[i]) >= 1){
document.write(arr[i] + " ");
}
}
</script>
new fiddle here
what you are telling javascript to do is only print the first character in the array of results matching your regex. you also have not accounted for the "space" character in your regular expression
to the best of my understanding this is what you are trying to accomplish - but if this is incorrect please clarify what results you are trying to achieve.
take a look at this fiddle
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z ]*/;
document.write(string.match(str));
</script>
note how ive used /[A-Z ]*/
including the space character in the matching set as well as an asterisk to denote matching any number of these characters. if you are attempting to only match the first word and stop at a space simply remove it.
in either case
here is a great article from the mozilla developer network explaining regex in all of its glory - pertaining specifically to its use with javascript
in case you decide you would like to take a gander at the 'manual'
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:
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.
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.
Here are some simple questions that might help you build up a straightforward approach:
What's a 'word'? How can you find all of them?
Can you put those words into an array of strings?
Can you loop through an array?
Can you increment a counter when looping?
Can you tell me how many letters are in a specific word?
Can you conditionally increment a counter based on an if statement?
Can you nest two loops?
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
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 ++;
}
}