JavaScript - Javascript Wildcard For Strings?
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; } Similar TutorialsHey, I'm working on an auto-suggest for our search function, but I am running into a wall (possibly due to lack of sleep). Basically, the user enters a search term, which searches our mySQL db, and if the search matches with a part number or description, it will output those results. My jam is that I would like the output to highlight the matching input, which I've gotten to work 95% correct. Code: for (var i=0;i<arr.length;i++) // Loop through results to indicate highlighting { // Test condition to see if input matches part number if (this.sInp.toLowerCase()==arr[i].value.toLowerCase()) // Tests to see if input matches part number and highlights input to match { var val = arr[i].value; var st = val.toLowerCase().indexOf( this.sInp.toLowerCase()); var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length); var span = _b.DOM.cE("span", {}, output, true); if (arr[i].value != "") { var br = _b.DOM.cE("br", {}); // Inserts line break span.appendChild(br); var small = _b.DOM.cE("small", {}, arr[i].info); // Produces second line (info or value) span.appendChild(small); } var a = _b.DOM.cE("a", { href:"#" }); var tl = _b.DOM.cE("span", {className:"tl"}, " "); var tr = _b.DOM.cE("span", {className:"tr"}, " "); a.appendChild(tl); a.appendChild(tr); a.appendChild(span); a.name = i+1; // Modified to submit on click a.onclick = function () { pointer.setHighlightedValue(); var formName = (pointer.oP.whereSubmit); if (formName != null) { var form = document.getElementById(formName); form.submit(); } return false; }; // End submit modification a.onmouseover = function () { pointer.setHighlight(this.name); }; var li = _b.DOM.cE( "li", {}, a ); ul.appendChild( li ); } else // Tests if input matches any part of description and highlights input to match { var val = arr[i].info; var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() ); var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length); var span = _b.DOM.cE("span", {}, output, true); if (arr[i].info != "") { var br = _b.DOM.cE("br", {}); span.appendChild(br); var small = _b.DOM.cE("small", {}, arr[i].value); span.appendChild(small); } var a = _b.DOM.cE("a", { href:"#" }); var tl = _b.DOM.cE("span", {className:"tl"}, " "); var tr = _b.DOM.cE("span", {className:"tr"}, " "); a.appendChild(tl); a.appendChild(tr); a.appendChild(span); a.name = i+1; // Modified to submit on click a.onclick = function () { pointer.setHighlightedValue(); var formName = (pointer.oP.whereSubmit); if (formName != null) { var form = document.getElementById(formName); form.submit(); } return false; }; // End submit modification a.onmouseover = function () { pointer.setHighlight(this.name); }; var li = _b.DOM.cE( "li", {}, a ); ul.appendChild( li ); } } // End Input Highlight My issue seems to be my conditional statement. Basically, the user's input must match the part number ("value") exactly for it to output the results is a specific format. I would like it to be able to have something similar to mySQL's wildcard ("%") it will search the entire part number ("value") and not just the beginning to find a match. Sorry if this doesn't make much sense, I will attempt to clarify if needed, but again running on 0 sleep. Thanks for any help. Ok, this is going to be a bit of an off the wall question and I'm not sure if it can even be done, but what I'm trying to do is prefill a form in an external iframe. The text fields in form that is in the external iframe all have a name of "U2FsdGV + a random generated string". There are 5 text fields all following the same pattern, I would like for it to post the value 1 in the first wildcard case it detects, then value 2 in the 2nd, etc... Here is my code so far: PHP Code: <script> function load() { var btn = document.getElementById('btnTest'); btn.onclick = function(){ var ifrm = document.getElementById('myiframe'); ifrm.contentWindow.document.forms['postingForm'].U2FsdGV*.value = 'Hello world!'; }; } window.onload = load; </script> 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, 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> Sorry for my beginner question but I am having some trouble getting this to work. I am trying to create a simple I=PRT calculator so it can calculate interest. But when you run it it adds the digits. Ex. 5+100=5100 instead of 105. Give it a try. My code is bellow.[CODE] // JavaScript Document alert("This is a simple calculator which will allow you to calculate the interest on a principle."); var principle = prompt("What is the amount you would like to calculate interest for?"); var rate = prompt("What is the interest rate. eg. For 3.9% write 3.9"); var term = prompt("How long in the period under calculation going to be? eg. For 1 year write 1"); var interest = principle*(rate/100)*term; var result = principle + interest; var a = "This means the interest is going to be $"; var b = " And the total to be paid is $"; var c = a + interest + b + result; alert(c); [CODE] Thanks in advance. How would i use a wildcard in String.match()? For example, I would like to see if a variable contains www.*.com, where the * can be replaced with anything. How could i go about doing that? Hi ya all, is it possible for Javascript to recognise 100 different labeled divs as one unit, so that I can unhiliten them onmouseout(on mouse over they are hilited). I realise that * is an operator and it can't be used as a wildcard, so is there some kind of substitue that can be used. I am trying to do something like this: Code: function goaway(id, status) { document.getElementById(id).style.visibility = status; goaway.onmouseout( fo-test * , 'hidden'); } the divs Id's are fo-test 1 thru to fo-test 100 most appriciate 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 + "~"; 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: 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! 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> 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 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> 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> 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 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? |