JavaScript - Searching For A String Inside Of An Array
Hi,
I am trying to search an array for a string and then if it is found alert it. I have found examples of how to iterate the array and how to use .IndexOf to return a true false statement as to whether the array includes the string, but i don't know what to do after that and how to display the string if its found. Any help appreciated.. Thanks Similar TutorialsHi guys im new here i have a project about searching string im am going to use javascript the program should look like this. Enter first word: abcd Search in first Word: ab then pop up ab found then if i type like sdg then pop up sdg not found something like this plss how can i do that hi guys, I'm having a bit of trouble with javascript... I'm searching for a string that starts with another string code: for (x in products ){ s = products[x].id.toString(10); v = "/\b"; v += idValue.toString(10); v += "/g"; alert(v); found = s.match(v); alert(found); } the variables are integers but since i'm searching for the beginning only i turned them into strings... the problem occurs when I add the \b it turns out gibberish.. any help will be gladly appreciated. p.s. if there is a faster way to do it without turning the variables to string also would be great to know. All right, to start, I'll summarize what I'm doing currently... - Asks the User to select a date (year, month, day) via drop-down boxes - Converts whatever the user inputs to a formal that will match a string value found in an imported array in a .js file ... And what I'm having trouble with: - Searching through the imported array for a matching value - Printing whatever block of the array matches the value, as well as any others that also match the value. For starters, because the array I'm working with is enormous, I'll just make one up here that is still in the same format. In working with the main code, assume that this is the cdr.js file: Code: var cdr = [ { "callid": "Guest User1", "start": "2009-05-11 15:08:40", "end": "2009-05-11 15:09:46", "duration": "66", }, { "callid": "Guest User2", "start": "2009-05-11 16:09:40", "end": "2009-05-11 16:09:47", "duration": "7", }, { "callid": "Guest User3", "start": "2009-05-12 12:10:30", "end": "2009-05-12 12:10:56", "duration": "26", }, { "callid": "Guest User4", "start": "2009-05-13 17:25:30", "end": "2009-05-13 17:26:30", "duration": "60", } ]; So basically I want the search to be based on that "start" value, though only the date (which I assume would be doable by using .substring()) Now here is the actual code of the program: Code: <html> <head> <script type="text/javascript" src="cdr.js"></script> <script> function init() { // Grab the values that the user has entered var theYear = (document.myForm.inputYear.value); var theMonth = (document.myForm.inputMonth.value); var theDay = (document.myForm.inputDay.value); // Convert them to something that will match the string theDate = (theYear + "-" + theMonth + "-" + theDay); // The search needs to go here } </script> <head> <body> Select a date which you would like to view the call statistics of: <form name="myForm"> <select name ="inputYear"> <option value="2009">2009</option> <option value="2008">2008</option> <option value="2007">2007</option> <option value="2006">2006</option> <option value="2005">2005</option> <option value="2004">2004</option> </select> <select name ="inputMonth"> <option value="01">January</option> <option value="02">Februrary</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name = "inputDay"> <option value="01">1</option> <option value="02">2</option> <option value="03">3</option> <option value="04">4</option> <option value="05">5</option> <option value="06">6</option> <option value="07">7</option> <option value="08">8</option> <option value="09">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <input type="button" onclick="init()" value="View Date"> </form> </body> </html> I've essentially left the section where the search code needs to be blank as I'm not even sure where to begin. Any help would be appreciated. Hi guys, I have an array which looks like this: var v=["It is my birthday today. ","How are you today. ","The weather is nice today. "]; I then, by using a function need to search for a specific word in the array, and if it is there, it alerts the word and "found", and if it isnt, it alerts the word and "not found". In the function below, a is the string/word which will be searched for in the array, and b is the array location to be searched. Therefore, if wordfind("birthday",0) was typed in, the value would be found. However, the code I have below is not working as I do not know how to make it so it knows that b is the array index to be searched and that a is the string value that will be searched for. Code: function wordfind(a,b){ var find = b.search(a) if(find==-1) alert(a+" not found") else alert(a+" found") } wordfind("birthday",0) Any help on this would be fantastic, Mike 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. hey guys im not new to javascript but arrays still confuse me exspecialy when put into loops ok say i had 2 arrays i have used jquerry to extract a question lets say this is the question How long is a piece of string? the answer is for this example infinite so what i want to do is search the question trough a array with 21984 and more in the future when it finds the match it then looks at the answers array at the same array length as where the question was found then sends the answer to a variable for later use could someone give me a example on how to do this please? Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["a", "b"]; Items [1] = ["c", "d"]; var i = 0; if(Items [i++][0] == "c"){ document.write("hello"); } </script> </script> <body> </body> </html> so im trying to search an array with this function its not working i tried using firebug but it showed no errors. I think its the i++ part i want to increment i each time it tries it. WAIT SORRY I SOLVED IT I solved it you can put in Pistol or shotgun for name Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["Pistol", "50", "2000"]; Items [1] = ["shotgun", "5000","1000"]; var i = 0; function chek(){ if(Items [i][0] == document.getElementById("name").value){ document.getElementById("a").value = Items [i] [1]; document.getElementById("acc").value = Items [i] [2]; i=0; } else { i++ } } </script> </script> <body> Dammage<input type="text" id="a" /> <br/> ACC<input type="text" id="acc" /> <br/> Name<input type="text" id="name" /> <br/> <input type="button" onclick="chek();" value="Chek" /> </body> </html> Is there anyway to make it more streamline so you dont have to click to increment? Hi guys, I'm trying to write a function such that it can be called, with a particular string specified in the call, and the function will then search a pre-defined array ("pages") of webpage URLs and headers in the form ["[www.sampleurl1.com] Sample Header 1. ", "[www.sampleurl2.com] Sample Header 2. "]; etc. etc., to see if the aforementioned string occurs in the "header" part of any of the indexes of the "pages" array, and then if it does, to alert "Found in x,y,z" where x y and z are the indexes of the "pages" array in which the specified string was found to occur. Here is what I have so far: Code: var pages=["[www.lboro.ac.uk] Loughborough University. ", "[www.oxford.ac.uk] Oxford University. "]; var founds=[] function findIdxsC(s){ for(i=0;i<pages.length;i++) if((pages[i].substring(pages[i].indexOf("]") + 1,pages[i].lastIndexOf("."))).match(/s/)) founds.push(pages[i]) } var array=founds.filter(findIdxsC) var arr2str=array.toStr; alert("Found in "+arr2str); findIdxsC("nIvERsi"); In theory, the above example should alert "Found in 0,1" because I have used the "match" command (so the search is case-insensitive) and the string "niversi" is found in the "header" parts of indexes 0 and 1. However, what it actually alerts is "Found in undefined". As far as I can see the problem lies with either the if-statement(and the associated command to "push" the indexes of "pages" for which the condition applies, to a new array, "founds") or with the filter and toString commands used towards the end. Perhaps it is one of these, or perhaps there is something else I am missing? Either way I would appreciate it if anyone could identify what in my code is causing the "Found in undefined" alert and suggest how I could rectify it, as it's causing me a bit of a headache Many thanks Hi, I have this loop: Code: for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); elabels[j].hide(); map.closeInfoWindow(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); count++; var p=j; } } which was useful for passing the p variable when it was just one number. but now I need to get that number every time j gets set (I understand that the j gets overwritten each time the loop goes through). What would be ideal is if p could become an array, the contents of which match the values that j has passed though during the loop cycle. I thought var p = new Array (j); minght do the trick, but obviously not... I hope that I'm explaining it OK, and that it's possible, and that somebody has an idea how to do it... Hello to all! How can I insert two values in an array in a salect option like the one below: Example: So I need in the "var op1 = new Option" an array thisarray[<?php echo"$user_name" ?>, <?php echo"$user_id" ?>] Data is being loaded by php from SQL Code: var newTextbox = document.createElement('select'); newTextbox.className = 'fn-select'; //First user in the populated select menu is the person Loged in var op1 = new Option("", ""); <----------[an array with two variables] ??? newTextbox.appendChild(op1); var txt1 = document.createTextNode('<?php echo"$user_name" ?>'); op1.appendChild(txt1); And then separate these variables and let the following function save them individualy: Code: function saveNote (note) { resetAjax(); var photoId = note.container.element.id; ajax.setVar('action', 'save'); ajax.setVar('photo_id', photoId); ajax.setVar('note_id', note.id); ajax.setVar('left', note.rect.left); ajax.setVar('top', note.rect.top); ajax.setVar('width', note.rect.width); ajax.setVar('height', note.rect.height); ajax.encVar('text', note.gui.TextBox.value); <------------- $user_name <------------- $user_id ajax.runAJAX(); var statusDiv = document.getElementById('PhotoNoteStatus'); ajax.onCompletion = function () {statusDiv.innerHTML = "<p>Note saved.</p>"; } return 1; } Whats up guys, have an interesting one for you... So I have a pretty simple survey form, with 5 checkbox answers, one of them being "None of the Above". All 5 are part of the same question1[] array. My goal is to have a function that unchecks the other 4 boxes when None of the Above is checked. The problem is that since None of the Above is part of the question1 array, it unchecks itself. So how do I separate this None of the Above option? After all, it is still a valid answer to question 1, so I don't want it to sit in a different array just because... Here's what I have now: Java: Code: function SetValues(Form, CheckBox, Value) { var objCheckBoxes = document.forms[Form].elements[CheckBox]; var countCheckBoxes = objCheckBoxes.length; for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = Value; } html: Code: <input id="question1" name="question1[]" type="checkbox" value="Answer 1"> 1<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 2"> 2<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 3"> 3<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 4"> 4<br> <input id="question1" name="question1[]" type="checkbox" value="None of the above" onclick="SetValues('form1', 'question1[]', false);"> None of the above <br> So again the issue with this code is that since None of the Above is inside the question1 array, it unchecks itself as well. thanks, rg 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? Hello, 1. I have the following script: function selectThis(id){ var locationstring = "process.php?value=" + id; ///// locationstring += "&bs=" + $('#bs_' + id).attr("selectedIndex"); locationstring += "&ad=" + $('#ad_' + id).attr("selectedIndex"); locationstring += "&ns=" + $('#ns_' + id).attr("selectedIndex"); locationstring += "&wt=" + $('#wt_' + id).attr("selectedIndex"); locationstring += "&in=" + $('#in_' + id).attr("selectedIndex"); document.location.href = locationstring; } With it I am getting a string with the value of the clicked button from an array and some other select field values that are listed in the same set of mysql results as the clicked button. BUTTON: <input name="button" type="button" onclick="selectThis('<? echo $rows['id']; ?>');" value=""> At the end of the script the page is redirected to in the script mentioned page with following string: process.php?value=1&bs=2&ad=3&ns=4&wt=5&in=6 (values are not real, so whatever the chosen value of the select field should apear in the link.) THIS WORKS FINE. 2. My problem is following: In order to be able to use var locationstring in other scripts as well I have removed var and have made it global. function selectThis(id){ locationstring = "process.php?value=" + id; ///// locationstring += "&bs=" + $('#bs_' + id).attr("selectedIndex"); locationstring += "&ad=" + $('#ad_' + id).attr("selectedIndex"); locationstring += "&ns=" + $('#ns_' + id).attr("selectedIndex"); locationstring += "&wt=" + $('#wt_' + id).attr("selectedIndex"); locationstring += "&in=" + $('#in_' + id).attr("selectedIndex"); } The problem is that later on when I use locationstring variable in other script I get only first variable in the string process.php?value=1 instead of process.php?value=1&bs=2&ad=3&ns=4&wt=5&in=6 3. Is it possible to make locationstring variable global and in a single line in order to be able to use the full string in other scripts or is there another solution. Thank in advance. So i've written up the code to do a lightbox esque overlay image gallery. everything is working smooth and fine. The only concern is that I have the following: lets say that I have a page that has multiple galleries. Obviously I would have to make each literal array with the gallery data different names, ex: Code: var _gallery1 = { 'images': [ { 'id' : 1, 'src' : "" } ] } var _gallery2 = { 'images': [ { 'id' : 1, 'src' : "" } ] } or would it be easier to do it multi dimensional? Code: var gallery_data = { 'gallery1': [ 'images': [ { 'id' : 1, 'src' : "" } ] ] 'gallery2': [ 'images': [ { 'id' : 1, 'src' : "" } ] ] } regardless of which direction I use... my main question is this: I have two variables which are the following: Code: galVariable = (i = location.hash.match(/#set=(.+)&photo=(\d+)/)) ? i[1] : null; galArray = _gallery2.images; I'm unfamiliar with a way of doing something along the lines of this, and having it actually work: Code: galVariable = (i = location.hash.match(/#set=(.+)&photo=(\d+)/)) ? i[1] : null; galArray = galVariable.images; obviously "galVariable" would be undefined... as i'm trying to get "_gallery2.images" but trying to use "galVariable" to point to "_gallery2" I'm familiar with solving a problem like this in PHP, not so much javascript. is there a JS function that can be used to ensure that it's using whatever "galVariable" equals to, and then that array's content is? Or is there a different way to go on about this. thanks in advance. if anyone needs some more clarification. please feel free to ask, and I'll respond asap. Hello everybody ! I'm searching for a javascript function that convert array to query string. Like this example : Code: var array = { a=1, b=2, c=3 }; to a=1&b=2&c=3 I'm using jQuery and the function .serialize() convert only html forms. Does someone know a function to do this ? Thanks ! I have var att=7,8,9 how can I convert these to an array so I can loop through the values? Hey. I have a string and I can return say, the fourth letter with output[3], but i can't assign a value to it for some reason: I am trying to make hang man Code: <!DOCTYPE html> <html> <head> <script src="jquery.min.js"></script> <script> $(document).ready(function(){ var word, output, wordLength, stringLength, newLetter, letters; var i, n, k, health, wcheck; word = "word"; output = ""; letters = ""; wordLength = word.length; for(i = 0; i < wordLength; i++){ output += "_"; } $("#inputLetters").keyup(function(){ newLetter = $("#inputLetters").val(); $("#inputLetters").val(""); letters += newLetter; wcheck = false; for(i = 0; i < wordLength; i++){ if(word[i] == newLetter){ wcheck = true; output[i] = newLetter; } } if(wcheck = false){ health++; } $("#letters").html(output + "<br />" + letters); }); }); </script> </head> <body> <span id="letters"> </span> <br /> <br /> <input id="inputLetters" type="text" /> </body> </html> Hello. I need help PLEASE ! I need to convert a string Quote: lalaw|lalaw1|lalaw2|lalaw3 in to Array The values I have in variable "tables" I want to create variable list which takes values from "tables" Than I want to split this, and put each value in to new array: I've started with: Code: var list = "tables"; var listArray = list.split("|"); for(i=0; i < listArray.length;i++) { //? how to put now values in to array? } Best Regards Leos Hi all, Forgive my ignorance, I'm quite new to Javascript... I'm looking to do two things: the first is to move elements of an array to the next index using a function. I have managed to do this like so: Code: var letters = ['h','i','j','k']; function moveElements(anArray){ var newArray = anArray; newArray.unshift(newArray[newArray.length-1]); newArray.pop(); } moveElements(letters); (this may or not be great, but it seemed to work) ... but I want the original array to reset to its original state if the function is called again (thus producing the same answer as opposed to shifting the elements again). Secondly, and this is the bit I'm really struggling with: I want to compare each letter of a string to elements within an array and display the indices. For instance: Code: var myArray = ['a', 'b', 'c', 'd', 'e', 'f']; var text = 'dead'; Hence I want the result '3,4,0,3'. I know the answer will use for and if statements but I can't wrap my head around it at all. Help would be appreciated, thank you. Hello All, I have a string array in a class file that contains 5 values, which I need to display on the jsp page. but when I send it to the javascript it prints [Ljava.lang.String;@104f8b8 . what do i do about it. I am a new to javascript. Is there a way to get my array data from the response object. Please help. |