JavaScript - Counting Occurences In A String
Hi,
I need to count how many times a keyword (input) appears in a string (str). I think I'm getting close with this: Code: var input = document.getElementById('autocomplete').value; var inp = input; for (var j = 0; j < gmarkers.length; j++) { var str=gmarkers[j].myname; var patt1=new RegExp(inp,'i'); if (str.match(patt1)) { found = true; var box = [inp]; var string1 = str; for (var i=0;i<box.length;i++) { nCount = string1.split(box[i]).length-1; alert(box[i] + ' is found ' + nCount + ' times<br>'); } but I can't get it to actually work. any ideas? thanks in advance. Similar TutorialsHello all! I've run into a few hour long snag and cant seem to get thru it. My homework says to write a JS program form with an identifying lable, an associated text area and 2 buttons. The buttons should have text that says "# letter occurrences" and one that says "# word occurrences". Each button should call an associated JS function. The # letter occurrences routine should print a table indicatin the number of occurrences of each letter off the alphabet in the text area, the # word occurrences routine should print a table indicating the number of one letter wors, the number of two letter words, the number of three letter words, up to 10 letter words ... So far here is what I have ..... <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>random</title> <script type="text/javascript"> var tableLetter="textArea"; var tableWord="textArea"; var lengthOfWord="tableWord.Length"; function ShowDiv(divName) { HideDivs(); if (document.all) { document.all.tableLetter.style.visibility = "visible"; } else { document.getElementById(divName).style.visibility = "visible"; } } function HideDivs() { if (document.all) { document.all.tableLetter.style.visibility = "hidden"; document.all.tableWord.style.visibility = "hidden"; } else { document.getElementById('tableLetter').style.visibility = "hidden"; document.getElementById('tableWord').style.visibility = "hidden";} } </script> </head> <body> <form name="form1" method="post" action=""> <textarea name="textArea" rows=6 cols=50> How many occurrences are in your sentence? </textarea> <br /> <input type="button" onClick="ShowDiv('tableLetter')" name="button1" value="# Letter Occurences"> <input type="button" onClick="ShowDiv('tableWord')" name="button2" value="# Word Occurences"> </form> <br /> <div id="text containter" style='width:420; height:85px; background:silver; position: absolute; '> <table> <div id='tableLetter' style="position:absolute; left:5px; top:10px"> <font color='#0000FF'>Letter Occurrences </font> </div> </table> <div id='tableWord' style='position:absolute; left:5px; top:10px; visibility:hidden;'> <font color='#0000FF'>Word Occurrences.</font> </div> </div> </body> </html> Hi Im new to javascript and need some help with a project I have, the task I have is: Create a page that can take a bloke of text and out put the following o How many times each letter occurs o How many spaces o How many words o How many times each word occurs o A list of things that are not words or special characters I think maybe use an array but im not sure, like I said im new to this so not too sure on how to do it. I know it would read into a file say a txt file and sort through it this way, possibly using some kind of loop to read through all of the text before sorting it and I know it might use variables. I know how to kind of work through the task I have, but to actually implement the mechanics of the javascript is something that I then struggle with Thanks to all that help. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Test Project</title> <script type="text/javascript"> var clicks=0; function linkClick(){ document.getElementById('clicked').value = ++clicks; } </script> </head> <body> <p align="center"><a href="http://www.google.ie" target="_blank" onclick="linkClick()">Google</a></p> <p align="center"> </p> <p align="center"><a href="http://www.google.ie" target="_blank" onclick="linkClick()">Google</a></p> <p align="center"> </p> <p align="center"><a href="http://www.google.ie" target="_blank" onclick="linkClick()">Google</a></p> <p align="center"> </p> <td colspan="3" valign="top">You have clicked my links <input id="clicked" size="1" onfocus="this.blur();" value="0" > times</td> <Script Language="JavaScript"> if ("clicks">3); { window.open('http://ie.yahoo.com','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no'); } </Script> </body> </html> I am a complete novice, I've spend most of today trying to research and learn Javascript. I would like my page to keep a count of how many times the links have been opened (this is happening) I would like a new pop up window to occur when the count gets to a specif value (this isnt happening) OR maybe to have a new hyperlink to appear that the user can then click on? Thanks in advance. I have a vertical menu in which the sub menu is a box that pops out to the right and the user can click boxes to make selections (input check boxes). I would like some way to indicate to the user after they have left the sub menu, that they have made selections within that sub menu. Perhaps a number after the menu item name, in which the number of sub menu selections are indicated in parenthesis? Is this possible? Hi all, I have an array holding 100 randomly generated integers between 0-9 inclusive...firstArray[99] how do i use a second array to keep count of how many times each integer is generated..secondArray[9] I feel stupid for asking a question about searching arrays, when there's a very similar thread that has been answered just recently on the first page; however, I'm still having trouble contemplating my own scenario. Basically, my program prompts the user for the length of the array and then asks the user to fill the array with words. Here is where I need help: I want to confirm if the user wants to search the array for those words. If so, the user will then be prompted to enter the word he wishes to search for; if found, the location of that word will be reported and the number of times the word has been searched for will be kept track of in a separate array. Here is what I have so far: Code: /* -- phase 3 ------------------------------------------------------ search for words the user asks for */ // search variables var response; var search; while (true) { // confirmation protocol response = confirm("Do you wish to search the lexicon for a word?") if (response) { search = prompt("What word would you like to search for?"); // alert("search"); } else { alert("Thank you for wasting my time."); break; } // begin search protocol for (i=0; i<words.length; i++) { if (search==words[i]) { alert("Word found at" +i+);} } // end for loop else {alert("word not found.");} // counter array/accumulator var hits = new Array(words.length); hits[i] = 0; for (i=0; i<words.length; i++) { if (words[i] == search) { hits[i] = hits[i] + 1; alert("This word has been searched for " +hits[i]+ "times."); } } // end for loop } // end while The problem with my search seems to be that the search is parsed through the for loop; if it finds the word it alerts me that it was found at i location, but then it continues through and sees that the search does not equal the other values in the array and reports it's not found as well. My counter array is completely off, and I'm really at a loss to figure it out. I can see that the problem might be that each new search resets the hits[i] to equal 0, so no matter how many times a word is searched for, it returns a count of 1. I really want this array to track the number of hits for each word searched for, but have no clue why it's not working. Thanks for any help I can get; and please, feel free to critique my coding style, I definitely need to improve. How can i go about showing on screen a count from an initial value to an end value over a set time period. Initial value = 0 End value = 2000 Time = 25 seconds I cant find an example of this anywhere, so I'm trying here to see if somebody can help Hey all, I have a simple example below showing how when I pass in the value of the value attribute of option node, and then use if operator to check whether parameter is a string or not, even though it's a string, it converts it to false boolean and triggers the else statement rather than calling a function: Code: <body> <select> <option value="createMsg">Add Message</option> <option value="removeMsg">Remove Message</option> </select> </body> Code: var menu = { handleMenu : function(callback){ if(callback === "string"){ menu[callback](); } else { console.log("Issue occurred") } }, createMsg : function(){ var content = document.createTextNode("Please give additional information."), heading = document.createElement("h1"); heading.appendChild(content); document.body.appendChild(heading); }, removeMsg : function(){ } } document.getElementsByTagName('select')[0].onchange = function(){ menu.handleMenu(this.value)}; callback should be a string so why is it saying otherwise? Thanks for response Hi all, as the title says i am trying to keep count of the number of words a user has typed into a textbox. I have an emoticon box, something like the one that you see when you reply/start a thread here. The mouseup event fires off when the user clicks on an emoticon to display it in the textbox. The problem here is, my code below does not start counting if an emoticon is added when theres nothing in the textbox (making the emoticon the first item). I can continue to add more smileys in and they will be counted in the word limit, but the first one will not be included in the count, unless the user clicks somewhere on the screen. How can i fix this problem? Code: //#message is the textbox $(document).ready(function() { var characters = 100; $("#remainder").append(characters+"words left"); $("#emoticonsbox").mouseup(function() { var remaining = characters - $("#message").val().length; $("#remainder").html(remaining+"words left"); }); }); Hello I have this snippet for controlling the number of characters entered in a textarea. It works. But, if I replace in this code the name "my_form" by "contact-form" and "my_text" by "message", it doesnt ! It looks like the keyword is " my_form ". You change that , and the script will not work! It turns out that I have to change those names because the form as it was already had those names my_form and message before I added this counter And I dont want to replace the names of the form in order to adapt them to this code snippet below. The question is why would the script not work if I have just replaced two words, which dont seem to be keywords of JS programming (my_form and my_text) <html><head> <title>(Type a title for your page here)</title> <script language=JavaScript> <!-- function check_length(my_form) { maxLen = 50; // max number of characters allowed if (my_form.my_text.value.length >= maxLen) { // Alert message if maximum limit is reached. // If required Alert can be removed. var msg = "You have reached your maximum limit of characters allowed"; alert(msg); // Reached the Maximum length so trim the textarea my_form.my_text.value = my_form.my_text.value.substring(0, maxLen); } else{ // Maximum length not reached so update the value of my_text counter my_form.text_num.value = maxLen - my_form.my_text.value.length;} } //--> </script> </head> <body> <form name=my_form method=post> <textarea onKeyPress=check_length(this.form); onKeyDown=check_length(this.form); name=my_text rows=4 cols=30></textarea> <br> <input size=1 value=50 name=text_num> Characters Left </form> </body> </html> I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
This is probably easy if I knew Javascript. Can someone show me the code to get the number "800014352" part from the url???? http://testebiz/ebizbtest/ShoppingCa...2/Default.aspx I am trying to use some string functions with no results. It appear what I'm using them on are not strings. my_string = document.getElementById("link5").onclick; document.write(my_string.lastIndexOf("5")); This gets nothing! And document.write(document.getElementById("link5").onclick.lastIndexOf("5")); gets nothing. BUT if I make a string and put what the onclick is set to with: my_string = "function onclick(event) { reveal(\"5\", \"2\", \"1864\")"; then my_string.lastIndexOf("5") will yield 34. So why is my original my_string = not working? And how can I get it to work? I was looking at this page, and came across "%" used in strange context. It appears that the mod operator can be used in Strings?? http://download.oracle.com/javase/tu...vaOO/enum.html What does this do/ mean? Thanks!!: System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); I need help with the following code below. It just doesn't turn out okay. Any ideas? Code: function changing() { A = document.exempel.Amount.value B = ("<%#Container.DataItem("Price_2_qty")%>") C = ("<%#Container.DataItem("Price_3_qty")%>") D = ("<%#Container.DataItem("Price_4_qty")%>") E = ("<%#Container.DataItem("Price_5_qty")%>") if (A < B) {document.exempel.Price.value = "<%#Container.DataItem("Price_1")%>"} else if (A = B && (!(A >= C))) {document.exempel.Price.value = "<%#Container.DataItem("Price_2")%>"} else if (A = C && (!(A >= D))) {document.exempel.Price.value = "<%#Container.DataItem("Price_3")%>"} else if (A = D && (!(A >= E))) {document.exempel.Price.value = "<%#Container.DataItem("Price_4")%>"} else if (A >= E) {document.exempel.Price.value = "<%#Container.DataItem("Price_5")%>"} } I have an array: Code: var array_123=["test1","test2","test3"]; I have a string: Code: var array_string = "array_" + "123"; I would like to use the value of array_string (array_123) as an array to parse out the values of it. But this isn't working: Code: for (var x in array_string) { var test_ary = array_string[x]; } Any help? Hi everyone... I'd written a code to split a string like below: Input string: a=>aa|b=>b||b|c=>cc and the output: a=>aa b=>b||b c=>cc I use .Match() to do that as below: var matches = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g) I want to use tha .Split() to split the above string. please help me... Hi, I'm coding a program to help people at my office to update the database, and the idea is to copy the content of an excel file and generate an sql from that, but I'm having a bit of trouble splitting the info into different tables: When copying everything the empty cells are read as tabulated, so I made a for that searches for more than one tabulator in a row (or find a \n and a following tabulator character) to split the info into several strings and format the info into a sql table, but I'm stuck he Code: var X=document.getElementById('opc'); var z=X.value.length; for(i=0;i<z;i++){ if(X.charAt(i)==' '&& X.chaAt(i+1)==' '){ char=X.value.substring(0,i-1); break; } } I tried with X.value(i) but I get the same error 'X.charAt is not a function', can someone tell me what am I doing wrong? Thanks. |