Advice on using word count javascript - javascript

I created a function that should generate a random paragraph, but I would like to get some advice on how can I display the number of times each word in the paragraph is used, once the button is clicked.... do you use something like a counter variable?
<html>
<head>
<title></title>
<script type="text/javascript">
<!--
var article = ["the", "be", "let", "done", "any"];
var noun = ["boy", "girl", "dog", "town", "car"];
var verb = ["drove","jumped", "ran", "walked", "skipped"];

Use regular expression match, and get the length of the result for each searched word.
For example:
var countThe = sentence.match(/the/g).length;
update: More generally:
function countOccurances(sentence, word){
var reg = RegExp(word,'g');
return sentence.match(reg).length
}
With a test:
var sentence = "This is the sentence that we are going to look in for testing -- not the real thing." ;
alert(countOccurances(sentence, "the"))

This will count the frequency of all words in a string.
function countWords(s) {
var a = s.match(/\w+/g);
var counts = {};
for(var i = 0; i < a.length; i++) {
var elem = a[i];
if(!counts[elem]) counts[elem] = 1;
else counts[elem]++;
}
return counts;
}

You can use javascript string.match is probably the easiest method.
function checkFor(wordsArray,inString){
returnObject={};
for(var i=0;i<wordsArray.length;i++){
returnObject[wordsArray[i]]=inString.match(new RegExp("([^A-Za-z]|^)"+wordsArray[i]+"([^A-Za-z]|$)","gi")).length
}
return returnObject;
}
checkFor(["hi","peter"],"I would like to say to you Peter, hi howdy hello, I think hi is the best of these greetings for you");
Returns Object {hi: 2, peter: 1};
Then just run this on each of the arrays with the sentance as the inString argument
EDIT:
To explain what this does,
It is a function where you can pass in an array of words to look for and it will output an associative array or object (JavaScript doesn't distinguish between the two) of the counts of those values
The function loops through each element in the words array
It then runs the regular expression /([^A-Za-z]|^)wordGoesHere([^A-Za-z]|$)/gi which is a bit complicated I admit
the regular expression checks for "WordGoesHere" and makes sure that is is a word not just part of another word, the ([^A-Za-z]|^) checks that the character before the word is not in the set A-Z or is the start of the string so basically allows spaces, commas, full stops and any other punctual thing you can imagine. ([^A-Za-z]|$) does the same except it checks for the end of the string
the gi is a flag stating a global search (don't just stop after the first match) and case insensitive
This site I find is invaluable for testing regular expressions

Related

Splitting sentence string into array of words, then array of words into arrays of characters within the array of words

I'm working through a problem on freecodecamp.com, and I want to see whether my code so far is doing what I think it is doing...
function titleCase(str) {
var wordArr = str.split(' '); // now the sentences is an array of words
for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
charArr = wordArr[i].split(''); //charArr is a 2D array of characters within words?
return charArr[1][1];
}
}
titleCase("a little tea pot"); // this should give me 'i', right?
Again, this is just the beginning of the code. My goal is to capitalize the first letter of each word in the parameter of titleCase();. Perhaps I'm not even going about this right at all.
But... is charArr on line 4 a multidimensional array. Did that create [['a'],['l','i','t','t','l','e'],['t','e','a','p','o','t']]?
In addition to ABR answer (I can't comment yet) :
charArr is a one-dimensional array, if you want it to be a 2d array you need to push the result of wordArr[i].split(''); instead of assigning it.
charArr.push(wordArr[i].split(''));
And don't forget to initialize charArr as an empty array
Few issues :
1. Your return statement will stop this after one iteration.
2. If one of the words have fewer then 2 letters (like the first one in your example, which is 'a') - you will get an exception at charArr[1][1].
Other then that, it is mostly ok.
It would probably help you to download a tool like firebug and test your code live...
You can do the following:
function titleCase(str) {
var newString = "";
var wordArr = str.split(' ');
for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
var firstLetter = wordArr[i].slice(0,1); // get the first letter
//capitalize the first letter and attach the rest of the word
newString += firstLetter.toUpperCase() + wordArr[i].substring(1) + " ";
}
return newString;
}
Also you need to remove the return statement in your for loop because the first time the for loop goes over the return statement, it will end the function and you will not be able to loop through all the words
Here you can learn more about string.slice() : http://www.w3schools.com/jsref/jsref_slice_string.asp

having an issue w/ .split in a JavaScript function that gets the max # of repeating chars per word in a string

I'm writing a JavaScript function that has to take in a string argument & determine the word or words with the maximum number or repeated (or most frequent) non sequential characters and return that word or words.
The way that I went about solving this problem was to first find the maximum number of times a character was repeated per word and record that number to use later in a function to test against every word in the string (or the array of strings as I later split it); if the word met the conditions, it's pushed into an array that I return.
My maxCount function seemed to work fine on its own but when I try to make it work together with my other function to get the words with max repeated chars returned, it's not working in JS Fiddle - it keeps telling me that "string.split is not a function" - I'll admit that the way I'm using it (string.split(string[i]).length) to analyze words in the string letter by letter is a bit unconventional - I hope there's some way to salvage some of my logic to make this work in the functions that can work together to get the results that I want.
Also, I don't know if I'm using Math.max correctly/in a "legal" way, I hope so. I've tried switching my variable name to "string" thinking that would make a difference but it did not even though my arguments are of the string variety and it's a string that's being represented.
Here's a link to my Fiddle:
https://jsfiddle.net/Tamara6666/rdwxqoh6/
Here's my code:
var maxCount = function (word) {
/// var maxRepeats = 0;
var numArray = [];
var string = word;
for (var i = 0, len = string.length; i < len; i++) {
//split the word('string') into letters at the index of i
numArray.push((string.split(string[i]).length) -1);
}
var max = Math.max(...numArray);
return max;
}
///console.log(maxCount("xxxxxxxxxxxxx"));
var LetterCount = function(string){
var repeatedChars = 0;
var wordArray=[];
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
var eachWord = stringArray[i];
var maxRepeats = maxCount(stringArray);
if (repeatedChars < maxRepeats) {
repeatedChars = maxRepeats;
wordArray = [eachWord];
}else if (repeatedChars == maxRepeats) {
wordArray.push(eachWord);
}
}
return wordArray;
};
console.log(LetterCount("I attribute my success to cats"));
//should return ["attribute", "success"]
*** I've tried to map this first function onto the array formed when I split my string at the spaces but it is just returned me an empty array (I also might not have been using map correctly in this example); I also have tried using valueOf to extract the primitive value out of the array from the first function which also didn't work. I'm not really sure what to do at this point or what angle to take- I feel if I understood more what was going wrong I could more easily go about fixing it. Any help would be much appreciated. Thanks!
You are passing an array to maxCount at line 20, while it expects a string:
var maxRepeats = maxCount(stringArray);
You should use:
var maxRepeats = maxCount(eachWord);
If you are getting split is not a function error then first make sure that your string isn't null by printing it on console. If it isn't null then confirm that its a string not an array or some other thing.

Stuck on my first program/game, Hangman

I'm working on a hangman game in jQuery. This is my first time working with writing my own code/program from scratch with no references to other peoples code (GitHub).
I created a "Start Game" button that starts the Hangman game. It will then grab a random word from an array I created, 'wordBank' and store it into a variable, 'word'. I use word.length and assign it to variable, 'wordLength'. I was not sure how to convert the wordLength (ex: 6 characters in the word) to 6 blank underscores: _ _ _ _ _ _
I was not sure if that should be part of a separate function either. I'm pretty good with HTML/CSS, but now I'm trying to learn to program and have been stuck the past day on this (I started it yesterday). I appreciate anyone who gives me advice. My code is below. Thanks.
var wordBank = ['apple', 'orange', 'peanut'];
// grab random word from array when user clicks start
function startGame() {
("#start").click(function(){
var word = wordBank[Math.floor(Math.random()*wordBank.length)];
var wordLength = word.length;
// convert wordLength into an underscore for each character
});
}
startGame();
You have several ways. (For each letter you get underscore and white space)
One is to use replace with regexp:
// Regex way.
var word = "abcd123456";
var userscores = word.replace(/.{1}/g, "_ ");
Other is to build underscores from word length:
// Build way.
var word = "abcd123456";
var wordLength = word.length;
var underscores = "";
for(i=0; i<wordLength; i++) {
underscores = underscores + "_ "
}
// now variable underscores has the underscores.
Happy gaming :)
First: I would keep it within the same function.
Second: I would just do a for loop and print a div with a class that has a
.underscore{
border-bottom: 2px solid black;
width:30px;
}
Like this:
var underscores ="";
for(var i=0;i<wordLength;i++){
underscores+= "<div class='underscore'></div>";
}
Hope this helps!
I think you are looking for a basic for loop, such as the following:
for (i=0;i<(word.length);i++) {
document.write("_ "); //or similar function
}
The above will output a number of underscores equal to your word length. Adjust this if you want to store them as a variable or other such function. I would consider assigning each letter in the string to an array with the value equalling "_ " by default, then changing the value to the actual letter when they guess correctly, or some other similar means, but abstract stabs at your game logic are beyond the scope of your question as it were posed.
Why don't you just store an underscore for each letter inside an array? That way you could access each underscore by it's index and decide how to display them later.
var result = [];
for(var i = 0; i < wordLength; i++){
result.push('_');
}
result.toString(); //returns _,_,_,_,_,_
result[0] //returns the first underscore
result[5] //returns the last underscore
result[2] = 'A'; // Replaces the third underscore with the letter 'A' (zero based)
result.toString(); //returns "_,_,A,_,_,_"
Later on, when you want to display the contents of the array you could just iterate it again. Something like this:
for(var i = 0; i < wordLength; i++) {
document.write(result[i] + ' ');
}

Extracting Strings Into an Array Regex

I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>

Splitting a String by an Array of Words in Javascript

I'm taking some text and want to split it into an array. My goal is to be able to split it into phrases delimited by stopwords (words ignored by search engines, like 'a' 'the' etc), so that I can then search each individual phrase in my API. So for example: 'The cow's hat was really funny' would result in arr[0] = cow's hat and arr[1] = funny. I have an array of stopwords already but I can't really think of how to actually split by each/any of the words in it, without writing a very slow function to loop through each one.
Use split(). It takes a regular expression. The following is a simple example:
search_string.split(/\b(?:a|the|was|\s)+\b/i);
If you already have the array of stop words, you could use join() to build the regular expression. Try the following:
regex = new RegExp("\\b(?:" + stop_words.join('|') + "|\\s)+\\b", "i");
A working example http://jsfiddle.net/NEnR8/. NOTE: it may be best to replace these values than to split on them as there are empty array elements from this result.
This does a case insensitive .split() on your keywords, surrounded by word boundries.
var str = "The cow's hat was really funny";
var arr = str.split(/\ba\b|\bthe\b|\bwas\b/i);
You may end up with some empty items in the Array. To compact it, you could do this:
var len = arr.length;
while( len-- ) {
if( !arr[len] )
arr.splice( len, 1);
}
Quick and dirty way would be to replace the "stop word" strings with some unique characters (e.g. &&&), and then split based on that unique character.
For example.
var the_text = "..............",
stop_words = ['foo', 'bar', 'etc'],
unique_str = '&&&';
for (var i = 0; i < stop_words.length; i += 1) {
the_text.replace(stop_words[i], unique_str);
}
the_text.split(unique_str);

Categories