JavaScript - Need Help With Strings And Substrings
I'm new at JavaScript and am trying to figure out a simple text calculator as seen on a science project website.
The project says the final program should calculate: 1. the number of sentences contained in the text, 2. the number of words in each sentence, 3. the number of letters in each word, 4. the average number of words per sentence, and 5. the average word length. I have pretty much everything (I think) but am being completely stumped by item number 2 and item number 4. The code is below. Can anyone help me understand what I should be doing for point number 2 and 4? I understand how to calculate and display the length of an item in an array and return it's values as 5,6,7,8 etc where the value is the length of the word, but i can't grasp how to calculate the number of items in an array to read 2,5,9 where the values are the number of words per each sentence...so confused! Below is my code...apoligies if it's sloppy...it's my first javascript code experience 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=utf-8" /> <title>Count</title> Code: Similar TutorialsI am new here. I've been trying to learn javascript, php, ajax, and others on my own, through the help of researching. I can't seem to manage figuring this out. I'm using a string "A B C" for sake of example. Variable d goes through a for loop checking for capital letters, to make substrings. d=0 finds A and makes the substring A. d=1 finds B and makes the substring AB. d=2 finds C and makes the substring ABC. It seems to me that: d=0 should be A d=1 should be B d=2 should be C. (which is what I want) Here's the actual code (obviously, the actual string being worked with is not 'A B C'): Code: response = response.replace(/([A-Z])(?![A-Z])/g, " $1") ; response1 = new Array(); caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ; a=0 ; q=0 ; for (a=0 ; a<=response.length-1 ; a++) { for (q=0 ; q<caps.length ; q++) { if (response.charAt(a) == caps.charAt(q)) { response1[response1.length] = response.substring(a,' ') ; }}} response1 = response1.filter(function(){ return true}) ; b=1 ; for (b=1 ; b<=response1.length-1 ; b++) { document.write(response1[b] + "<br />") ; } } Hi, I know how to replace all the + signs in a url string by spaces, like this: newstring=oldstring.replace(/[+]/g," "); but how do I replace a substring by a comma easily? This doesn't do it: newstring=oldstring.replace(/[&menuitems]/,","); Thanks in advance for any help. How do I join strings? I tried below but get an error. var a += document.getElementById("PICKUP_TYPE").value + "~"; var a += document.getElementById("PICKUP_ADDRESS").value + "~"; var a += document.getElementById("PICKUP_ADDRESS2").value + "~"; Okay so I have this code for HMTL5 Canvas, however this is a JavaScript directed question not a Canvas question. Code: <script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); cxt.moveTo(0,400); cxt.lineTo(50,a); cxt.lineTo(100,b); cxt.lineTo(150,390); cxt.lineTo(200,300); cxt.lineTo(250,285); cxt.lineTo(300,299); cxt.lineTo(350,250); cxt.lineTo(400,325); cxt.lineTo(450,275); cxt.lineTo(500,300;); cxt.stroke(); </script> That will draw a line graph, however I want to get the coordinates from a variable in the URL. So it may be example.com/a=500&b=600 . How would I retrieve these two variables and then insert in to they're respective places? Any help greatly appreciated, please make it as simple as possible - I'm good with my PHP now but JavaScript is all new Hello, A quick summary to inform you on what I'm trying to accomplish and then the question. If you want to skip to the question first, I have it in red letters lower down. Just figured I'd answer the "why are you doing it this way" question first. I am writing a tool in JavaScript in which a user selects various options via checkboxes and then a pre-engineered scenario image for a product matching those selections is displayed. Here is the basic workflow of the code: 1. The code runs through the checkboxes and based on whether the boxes are checked or not, adds a value of "1" or "0" to a string. There are some dashes added into the string to visually divide some categories of options. Here is an example of the resulting string: 0-0011100-101100 2. A variable named scenarioID holds the value of the resulting string. A switch statement is run which assigns a name to the scenario based on the scenario ID. Here is an example: PHP Code: switch(scenarioID){ case "0-0011100-101100": var scenarioName="Scenario 1"; break; } 3. The scenarioName variable is then used to pull up an image with the corresponding name. For example, if the scenarioName variable has a value of "Scenario 1" then an image named "Scenario 1" is displayed. --------------------------------------------- So here is where I am running into an issue: I have some scenario names that multiple scenario ID's match because they apply whether a specific checkbox is selected or not. Currently, I am still able to apply the correct name to the scenario by simply having multiple switch statements apply to the same scenario name. For example: PHP Code: switch(scenarioID){ case "0-0011100-101100": var scenarioName="Scenario 1"; break; case "0-1110011-101101": case "1-1110011-101101": var scenarioName="Scenario 2"; break; } However, I have some scenarios in which up to 3 options may apply whether or not they are checked. This means that I have to have 8 different switch cases (scenario ID's) for a single scenario name. Is there a way for me to wildcard the switch cases so that I can specify which items don't matter for a scenario? Something like the following example? PHP Code: switch(scenarioID){ case "0-0011100-101100": var scenarioName="Scenario 1"; break; case "*-1110011-101101": var scenarioName="Scenario 2"; break; } Hi All, I'm trying to convert a string based on the contents of another string. For example, I have two strings - "Purple" and "Orange" and a variable "P" - I want the script to look at the word "Purple" and everytime is sees the letter "P", assign this to a third variable (result variable) - if the letter it's looking at is not a "p", I want it to take that character from "Orange" and add it to the result string. So the result would be "Prapge". This is the code I have so far, and it doesn't work, absolutely stumped as to why ... Code: function fillInChar(targetString, otherString, newChar) { var splitTarget = targetString.split(''); var splitOther = otherString.split(''); var resultArray = newArray(splitTarget.length); var holdVar = ''; for (var position = 0; position < splitTarget.length; position = position + 1) { if (splitTarget[position] != newChar) { var holdVar = splitOther[position]; resultArray[position] = holdVar } else { resultArray[position] = newChar } } return resultArray } document.write('IF VISIBLE - LOOP IS VIABLE' + '<BR>') var testVar = fillInChar('purple', 'orange', 'p'); document.write('HELLO WORLD!!! .... ' + testVar); I'm trying to write a pi calculator that shows a comparison of the calculated value to the actual value. It works, but the output of the comparison shows only the first two decimal spots, followed by two 9s. Why is it showing two 9s and how can I make it more precise? Code: <head> <title> Pi Calculator </title> <script language="JavaScript"> function calcpi(digitsn) { p = 1; s = 0; for (c = 3; c < digitsn; c += 2) { if (s == 0) { p -= 1/c; s = 1; } else { p += 1/c; s = 0; } } p *= 4; return p; } function hid(input) { //Highlight Incorrect Digits pi = "3.14159265358979323846".split(''); input = input.toString().split(''); result = ""; for (c = 0; c < input.length; c++) { if (input[c] != pi[c]) { //result += "; " + input[c] + "!=" + pi[c]; result += "<span style='background-color:red'>" + input[c] + "</span>"; } else { result += input[c]; } } return result; } </script> </head> <body> Repeat algorithm x many times:<br/> <input type="text" value="10000" id="digitsx"/><br/> <input type="button" onClick="document.getElementById('answer').value=calcpi(parseInt(document.getElementById('digitsx').value)).toString()" value="Calculate"/><br/> Result:<br/> <input type="text" readonly id="answer"/><br/> Correct value:<br/> <input type="text" readonly value="3.14159265358979323846"/><br/> <input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/> <div id="comparison"/> </body> Hi, I know virtually nothing about js so here goes: I use the following script: Code: <script type="text/javascript">var showNav = false;var params='clubID=1784&compID=8041&leagueTable=y&orderTBCLast=Y&colour=147C99';var colour = '147C99';</script> The variable which needs to be called from another page is 'compID' - as I have about 20 competitions rather than hard-coding each page I hoped to generate this from the following: infocus/respage.php?cid=8041 <--- where I can change the compID from the 'calling' page. In my absolute naivety I thought I could simply change the code to this: Code: <script type="text/javascript">var showNav = false;var params='clubID=1784&compID=cid&leagueTable=y&orderTBCLast=Y&colour=147C99';var colour = '147C99';</script> But as the learned among you will realise this just doesnt work - any help appreciated! Strings,, Broken Links, and Variables --HELP! I have a page with over 600 lines of code that I need to fix, the problem is as such: The page contains about 200 links, the problem is that the link tags are all messed up,, instead of the URL's they all got replaced with xxxxx so instead of: <a href="http://mystore.com/product1">product1</a> it would read: <a href="http://mystore.com/xxxx">product1</a> each product has to link to it's own page .... i.e: product1 goes to /mystore.com/product1,,, and so on I need help writing a script or performing some sort of function, that will take the text in between the <a></a> tags and insert it into it's own tag instead of the xxxxx so it would see <a href="http://mystore.com/xxxx">BaseBall Gloves</a> and convert that line into <a href="http://mystore.com/BaseBall%20Gloves>BaseBall Gloves</a> -- OUTPUTS: the ideal way would be if it could replace the existing source (kind of how you can do a find and replace),, if that's not possible, it would need to output all the existing source code with the modified <a> tags to a new window, and then I can copy that code into a new page. I've tried using regular expressions and different functions but can't get it to work. I really appreciate your help.. Thanks. I am now working on a utility function that will gather the indexes for substring matches found in a string. There is an academic mystery I am puzzling over Code: function getMatchIndex(a, b) // a: sting to search b: what to search for { var out = new Array(); if(a.lastIndexOf(b) > -1) // at least two matches, ****! there could be more { if( (a.substr(a.indexOf(b) + b.length, a.lastIndexOf(b))).length > b.length ) { var stp = parseInt(a.lastIndexOf(b)) - (parseInt(a.indexOf(b)) + parseInt(b.length)); alert(stp) alert( (a.substr(a.indexOf(b) + b.length, stp)).length+' : '+a.substr(a.indexOf(b) + b.length, stp)); } else { out[out.length] = a.indexOf(b); out[out.length] = a.lastIndexOf(b); return out; } } else if(a.indexOf(b) > - 1 && a.lastIndexOf(b) == -1) { out[out.length] = a.indexOf(b); return out; } else if(a.indexOf(b) == -1) { out = 'no matches'; return out; } else { var splitStr = new Array(); splitStr = a.split(b); /* possibilities: 1: one match at the begining or end -- leaves one significant item 2: one match somewhere after the beginning and before the end. -- gives two matches. */ for(var i = 0; i < splitStr.length - 1; i++) // don't want the last segment length { out[out.length] = splitStr[i].length } } } getMatchIndex('xxxi5ixxxxxxxi5ixx', 'i5i'); in the following code snippet: Code: if( (a.substr(a.indexOf(b) + b.length, a.lastIndexOf(b))).length > b.length ) { var stp = parseInt(a.lastIndexOf(b)) - (parseInt(a.indexOf(b)) + parseInt(b.length)); alert(stp) alert( (a.substr(a.indexOf(b) + b.length, stp)).length+' : '+a.substr(a.indexOf(b) + b.length, stp)); I am trying to get the sub string between the end of the first match to the beginning of the last match. The 'if' test passes, but I have to parseInt the values to get the proper value for stp. SO, the question is, what is the actual data type of an index value obtained from a string. (It would appear to be a string; having to use it an a math expression doesn't work without parseInt). (I hope I haven't posted too much code) Thank you in advance. Hello all. I'm working with a simple shopping page. I basically need to add up all of the values that are found in my query string, and display them as a total on my page. I know how to retrieve each value individually, however I'm a little confused on how to add up the values that are only found in the query string. Please keep in mind, I'm very new to javascripting, and probably won't understand in-depth coding. I have a lot more code to go with this, but I don't think it's required for my question.. Any help would be appreciated! Code: <javascript> var parameters = new Array( ); // <![CDATA[ var qs = document.location.search.substring( 1, document.location.search.length ); var params = qs.split( "&" ); for (var x=0 ; x < params.length ; x++) { var pair = params[ x ].split( "="); parameters.push( new Parameter( pair[ 0 ], pair[ 1 ] ) ); } function get_parameter_value_for_name( name ) { for( var x = 0 ; x < parameters.length ; x++) { if( parameters[ x ].name == name) { return parameters[ x ].name; } } return " "; } function get_parameter_value_for_value( name ) { for( var x = 0 ; x < parameters.length ; x++) { if( parameters[ x ].name == name) { return parameters[ x ].value; } } return " " ; } //]]> </script> I believe the problem with my code here is that for some reason, on the equation for VertY.. it is being treated as a string.. I want it to be a math equation, but it treats it as text. (ie -1 + 1 should be 0, but it says it is -11) I believe this is the problem code: form.VertY.value = ((a * (form.VertX.value * form.VertX.value)) + (b * form.VertX.value) + (c)) Code: <html> <head> <title>Untitled</title> </head> <script type="text/javascript"> function quad(form) { a = form.a.value b = form.b.value c = form.c.value form.Dis.value = (b * b) - (4 * a * c) form.VertX.value = (-b) / (2 * a) form.VertY.value = ((a * (form.VertX.value * form.VertX.value)) + (b * form.VertX.value) + (c)) if (a == 0) { alert("ERROR, EQUATION MUST BE QUADRATIC") } else { if (form.Dis.value > 0) { form.NumSol.value = 2; form.SolOne.value = ((-b) + Math.sqrt(form.Dis.value)) / (2 * a) form.SolTwo.value = ((-b) - Math.sqrt(form.Dis.value)) / (2 * a) } else if (form.Dis.value == 0) { form.NumSol.value = 1; if (((-b) - Math.sqrt(form.Dis.value)) == 0) { form.SolOne.value = ((-b) - Math.sqrt(form.Dis.value)) / (2 * a) form.SolTwo.value = "NO SOLUTION" } else { form.SolOne.value = ((-b) + Math.sqrt(form.Dis.value)) / (2 * a) form.SolTwo.value = "NO SOLUTION" } } else { form.NumSol.value = 0; form.SolOne.value = "NO SOLUTION" form.SolTwo.value = "NO SOLUTION" } } if (a > 0) { form.Open.value = "Up" } else { form.Open.value = "Down" } } </script> <body> <form name="form1"> <table border="2" align=center> <center> <tr> <td align=center valign=middle><input type="text" name="a" size=3> x^2 + <input type="text" name="b" size=3> x + <input type="text" name="c" size=3> </td> </tr> <tr><td align=center valign=middle> <input type="button" value="Calculate" onClick="quad(this.form)"> </td></tr> <tr><td align=center valign=middle>Discriminant: <input type="text" name="Dis" size = 7 /></td></tr> <tr><td align=center valign=middle>Number of Solutions: <input type="text" name="NumSol" size = 2 /></td></tr> <tr><td align=center valign=middle><b>Solution 1: </b><input type="text" name="SolOne" size = 10 style="font-weight:bold;" /></td></tr> <tr><td align=center valign=middle><b>Solution 2: </b><input type="text" name="SolTwo" size = 10 style="font-weight:bold;" /></td></tr> <tr><td align=center valign=middle>Your graph will open: <input type="text" name="Open" size = 4 /></td></tr> <tr><td align=center valign=middle> Vertex: ( <input type="text" name="VertX" size = 2 /> , <input type="text" name="VertY" size = 2 /> ) </td></tr> </table> </form> </center> </body> </html> Hello, I very new to this language and I still feel like I'm not grasping it... But, anyways, I'm doing a thing for school and I have to let the user input a string. I need to save the string and turn it into an array. For every word that is less than five letters I put "little" at the beginning of the word and for every word that is more than five letters I put "big" at the end of each word. Then I need to return the new string into output. I think I wrote the code really incorrectly, so any tips/advice would be much appreciated! Also, I don't understand adding user input into a code if that makes sense. The tutorials/lessons I've been looking at all say to put information into an array first and then mess with it. But, what if you don't have information in the array until the user puts it in? And once they enter it, then you mess with what they entered. I can't seem to get how to do that. Thank you for your time Code: function texter(newText){ var oldHTML = document.getElementById('outputPrompt').innerHTML; document.getElementById('outputPrompt').innerHTML = newText+"<br />"+oldHTML; console.log(newText); } function menuTwo(){ var userInput = document.getElementById('input').value; var correctedInputArray = userInput.toLowerCase().split(" "); var mainTwo = new Array([""]); for(var i=0; i<correctedInputArray.length; i++){ var thisWord = correctedInputArray[i]; var lessFive = 5; var moreFive = 6; var restOfWord; if(lessFive<5){ mainTwo[i]=thisWord+"-little"; }else if(moreFive>6){ mainTwo[i]="big-"+thisWord; } else{ restOfWord = thisWord.substr(1, thisWord.length-1); } } output = mainTwo.join(" "); texter(output); } </script> </head> <body> <h1>Document</h1> <input type='text' id='input' /> <input type='button' onclick='menuTwo()' value='submit'/> <p id='outputPrompt'>Please enter 1,2,3 or exit only</b> </p> </body> </html> Code: <html> <head> <title> Caught </title> <script language="JavaScript"> <-- hide me // get user to add name var name_entry = prompt ("Please Enter your Name!", "James"); // declare some short strings var stating = ", I knew you did it!" var told = "I told you that I would find out" var mistake = "I guess you just made a mistake entering your name," var punish = "Now go back to your room" // construct some longer strings var stating_name = name_entry + stating; var mistake_name = mistake + name_entry; // stop hiding me --> </script></head><body> <h1> OI Stop! </h1> <script language="JavaScript"> <!-- hide me document.writeln(stating_name + "<br>"); document.writeln(told = "<br>"); document.writeln(mistake_name = "<br>"); document.writeln(punish = "<br>"); // show me --> </script> </head> <p> <FORM> <INPUT TYPE="button" VALUE="To Your Room" onClick="history.back()"> </FORM> </p> </body></html> It will not show my strings and variables?? Please Help!! Hello everyone, I'm new to using regular expressions with javascript. I'm trying to search a string for instances of a substring with a particular prefix, followed by some numerical digits. So for instance my larger_string is: "This is a string ABCD12 EFGH124 ABCD76 EFGH90" And initially I want to find all substrings starting 'ABCD', with two following numerical digits. I can do it like this: var answer = larger_string.match(/ABCD\d\d/); But I'd really like to pass the 'ABCD' part in as a string itself, myString, as I'd then like to set myString to 'EFGH' and others, to repeat the search for those. I'm struggling with the syntax for creating a regular expression froma string. So I can do this: var reg = new RegExp("ABCD", "g"); but, this doesn't work: var reg = new RegExp("ABCD\d\d", "g"); and similarly I can do this: var myString = "ABCD"; var reg = new RegExp(myString, "g"); but, this doesn't work: var myString = "ABCD\d\d"; var reg = new RegExp(myString, "g"); What is it that I'm doing wrong here? Thank you I'm guessing that this question has a simple answer, but after spending quite awhile trying, I still haven't figured it out. It's probably partly because I'm not certain about my js terminology yet. Here's the objective: The script reveals a modal window containing a form. It also makes visible a transparent png to darken the background. There should be a nice fade animation, both in and out. It's mostly done. The problem is that the animation currently affects only .popup and .darken snaps on and off. The way I've been trying to do this is to find a way to join darken.css() and popup.css() that occur just before the .animate(). That seemed like it should then animate both. Any help would be appreciated. Thanks in advance! The full code is copied below. Code: $(function () { $('.bubbleInfo').each(function () { // options //var distance = 10; var time = 250; var hideDelay = 800; var hideDelayTimer = null; // tracker var beingShown = false; var shown = false; var trigger = $('.trigger', this); var popup = $('.popup', this).css('opacity', 0); var darken = $('.darken', this).css('opacity', 0); // set the mouseover and mouseout on both element $([trigger.get(0), popup.get(0)]).mouseover(function () { // stops the hide event if we move from the trigger to the popup element if (hideDelayTimer) clearTimeout(hideDelayTimer); // don't trigger the animation again if we're being shown, or already visible if (beingShown || shown) { return; } else { beingShown = true; // reset position of popup box darken.css({ display: 'block' }) popup.css({ //top: -200, //right: 0, display: 'table' // brings the popup back in to view }) // (we're using chaining on the popup) now animate it's opacity and position .animate({ // top: '-=' + distance + 'px', opacity: 1 }, time, 'swing', function() { // once the animation is complete, set the tracker variables beingShown = false; shown = true; }); } }).mouseout(function () { // reset the timer if we get fired again - avoids double animations if (hideDelayTimer) clearTimeout(hideDelayTimer); // store the timer so that it can be cleared in the mouseover if required hideDelayTimer = setTimeout(function () { hideDelayTimer = null; popup.animate({ // top: '-=' + distance + 'px', //removes vertical movement opacity: 0 }, time, 'swing', function () { // once the animate is complete, set the tracker variables shown = false; // hide the popup entirely after the effect (opacity alone doesn't do the job) popup.css('display', 'none'), darken.css('display', 'none'); }); }, hideDelay); }); }); }); Currently, this is my code: PHP Code: function createRow(){ $.post("php/qaRowEntry.php", { }, function(data){ $("#qaresultrowentry").text(data); test(); }); } It grabs visible data and $_SESSION data, that I know of it. However, I need to be able to retrieve or create variables based on the response. It would look like this: I run a code similar to the one above, and when I get the php script's response, javascript now has 3 filled variables that I can use. Is it possible? I saw one suggestion of setting async to false, but that it can cause the browser to hang. That's not an acceptable reaction. Thanks for your suggestions! Hi, I was working on this problem that asks me to return an array of scores for each string (only for its content part, not URL) in the global variable, which is an array. For example, alert a score of 0 if the string z is not found, 1 if found once, and 2 for twice. My problem is that I can get the code to alert if it has found the word (ex. "the"), but I cannot manage to : a) Assign separate scores for each string. b) Make the search case insensitive i.e. "the" will appear in 0,1, but not in 2, where it is capitalized I would appreciate any help! [CODE] var c = ["[www.facebook.com] Facebook is the best social networking site to coccent with your friends. ", "[www.google.co.uk] Google is the worldwide search engine. ", "[www.bbc.co.uk] The best news source for starting your day. "]; function findScore(z) { for (var i=0; i<c.length; i++) { var a = c[i].toString(); var b = a.search(z); if(b>-1) { alert (z + " found in array " + i); } } } findScore("the"); [CODE] Sorry for not being able to wrap the code! I am attempting to manipulate a long text string with javascript. This text string may have one or more occurrences of a string which starts with a particular string and ends with another string. So, for example, text that starts with 'nam' and ends with 'sit' in this example: Quote: Lorem ipsum dolor sit amet, consectetur adipiscing elit nam aliquam leo sit amet nibh tincidunt ultricies. Nullam nam feugiat velit sit amet dui scelerisque id ornare nulla ultricies. I want to prepend another string before the nam and append another after the sitt, to give me: Quote: Lorem ipsum dolor sit amet, consectetur adipiscing elit before nam aliquam leo sit after amet nibh tincidunt ultricies. Nullam before nam feugiat velit sit after amet dui scelerisque id ornare nulla ultricies. I think the way to do this is via RegExp, but I'm insufficiently familiar with this to know how to write the expression. Can anyone help me out? |