JavaScript - Search In Body, Place Matches Into An Array
Hello everybody
I'm working on a tiny personal project, that only needs a little push to be finished. As I'm not a skilled enough scripter, I had to google around, but without any result exactly same as mine. What I'd like to know, how can I search in the body for strings surrounded by other strings that signs that the string I want is between them? example: Code: I'm a part of the body :3 // <- not surrounded part of the body [cust]You want me in your array :)[/cust] // <- this one is surrounded I won't get into your array :( // <- this one is not, just like the most of the body I have no snippet that could help me. Thank you in advance Similar TutorialsI'm having major pains trying to figure this out. I'm kind of new to Javascript, I need to open a text file from an external server, store each line in an array, then search that array for a certain word (HIGH), and if it exists then write something to the webpage, and if not, write something else. Here is what I have so far: Code: <html> <head> <title>Test</title> <script> <!-- function test(x) { if (wxd1txt.readyState === 4 && wxd1txt.status === 200) { // Makes sure the document is ready to parse and Makes sure it's found the file. var wxd1text = wxd1txt.responseText; var wxd1array = wxd1txt.responseText.split("\n"); // Will separate each line into an array var wxd1high = wxd1array.toString(); //Converting the String content to String //var highsearchreg = new RegExp("HIGH"); //var wxd1high = wxd1array[x].search(highsearchreg); document.write(wxd1high); if (wxd1high.search("HIGH") >= 0){ document.write("HIGH RISK");} else { document.write("NO RISK");} } } //--> </script> </head> <body> Hi! <script> <!-- var Today = new Date(); var ThisDay = Today.getDate(); var ThisMonth = Today.getMonth()+1; var ThisYear = Today.getYear(); var Hour = Today.getHours(); var Day2 = Today.getDate()+1; var Day3 = Today.getDate()+2; if (navigator.appName != "Microsoft Internet Explorer") { ThisYear = ThisYear + 1900;} if (ThisMonth < 10) { ThisMonth = "0" + ThisMonth;} if (ThisDay < 10) { ThisDay = "0" + ThisDay;} if (Hour == 2 || Hour == 22 || Hour == 23 || Hour == 0 || Hour == 1) { var wxHourd1 = 0600} else if (Hour >= 3 && Hour <= 10) { var wxHourd1 = 1300;} else if (Hour >= 11 && Hour <= 13) { var wxHourd1 = 1630;} else if (Hour >= 14 && Hour <= 16) { var wxHourd1 = 2000;} else if (Hour >= 17 && Hour <= 21) { var wxHourd1 = 0100;} //var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/"+ThisYear+"/KWNSPTSDY1_"+ThisYear+""+ThisMonth+""+ThisDay+""+wxHourd1+".txt"; var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/2010/KWNSPTSDY1_201005101300.txt" //(High risk day for testing) //document.write(wxurld1); //Use this to verify this section is working if (window.XMLHttpRequest) { wxd1txt=new XMLHttpRequest(); } else // IE 5/6 { wxd1txt=new ActiveXObject("Microsoft.XMLHTTP"); } wxd1txt.open("GET", wxurld1, true); wxd1txt.onreadystatechange = test(); // --> </script> </body> </html> When added to a webpage, nothing shows up except the "Hi!" and there are no errors in the Javascript Console in Google Chrome. Is this possible with Javascript, and if so, what am I doing wrong or not doing? Also, I have 2 URLs, one is a text file that has the HIGH text I want for an example, the other is the current file, which shouldn't have HIGH in it (unless the weather in the US turns really bad) I want to have a simple code such that some data is stored in array. When we create a search box it has to give suggestions from the data stored in array. The question is Allow the search function to start anywhere within the name, rather than just at the start (so searching for "icha" would match "Richard". can any one help? Reply With Quote 01-14-2015, 05:08 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts Code: <script type = "text/javascript"> var names = ["Brian", "Peter", "Richard","Thomas"]; for (var i =0; i<names.length; i++) { var str = names[i]; var n = str.search(/icha/i); // the i flag means case insensitive if (n != -1) { // match found alert (i + " " + n); // 2 1 that is, the match is found at the third array item at the second character } } </script> Or:- Code: <script type = "text/javascript"> var names = ["Brian", "Peter", "Richard","Thomas"]; var pattern = "icha"; for (var i =0; i<names.length; i++) { var str = names[i]; var s = new RegExp(pattern,'i').test(str); // the i flag means case insensitive if (s) { alert ("Match found at array index " + i); // 2 } } </script> All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit. Okay, this should be an easy one. I'm a JS newb, so be kind The code I have right now is an autosuggest feature, but currently, it only finds exact matches, not partials. I want it to find partials. I know the line of code I need to rewrite, but I can't figure out what JS function to use. For example, if a user types "pizza", i want "pepperoni pizza" to show up, not just things that start with "pizza". Code: // str is the string that the user is typing in // this.aNames is an array containing all the possible strings to match against // aList is the list of matches from aNames when compared to str autoCompleteDB.prototype.getMatches=function(str,aList,maxSize) { /* debug */ //alert(maxSize+"ok getmatches"); var ctr=0; for(var i in this.aNames) { if(this.aNames[i].toLowerCase().indexOf(str.toLowerCase())==0) /*THIS LINE NEEDS TO BE CHANGED*/ { aList.push(this.aNames[i]); ctr++; } if(ctr==(maxSize-1)) /* counter to limit no of matches to maxSize */ break; } }; hi, I've been making a search box, which works as it should like this: Code: function searchLocations() { var input = document.getElementById('tb').value; if (!input) { alert("please enter a name"); } else { for (var j = 0; j < gmarkers.length; j++) { if (gmarkers[j].myname.toLowerCase() == input.toLowerCase()) { gmarkers[j].show(); myclick(j); } } } } but then if the user types a term that doesn't match, it does nothing. So I wanted an alert, which I figured would go like this: Code: function searchLocations() { var input = document.getElementById('tb').value; for (var j = 0; j < gmarkers.length; j++) { if (input.toLowerCase() == gmarkers[j].myname.toLowerCase()) { gmarkers[j].show(); myclick(j); } else alert("no results found"); } } or this: Code: function searchLocations() { var input = document.getElementById('tb').value; for (var j = 0; j < gmarkers.length; j++) { if (gmarkers[j].myname.toLowerCase() !== input.toLowerCase()) { alert("no results found"); } else { if (gmarkers[j].myname.toLowerCase() == input.toLowerCase()) { gmarkers[j].show(); myclick(j); } } } } but either way pops an alert, even if the search term is valid, and locks the page up. which is not quite what I was looking for. any suggestions? Hi Guys, I am trying to make a function that will search for a substring, in this case 'http://instagr.am/p/' within a text area on a form then add '[embed]' & '[/embed]' tags around it. I have currently got the following code Code: <script type='text/javascript'> function show_alert() { str = formname.elements['inputid'].value; arr = (str.split(' ') + '<br />'); jQuery.each(arr, function() { if (arr.indexOf('http://instagr.am/p/') >= 0) { alert('An http://instagr.am/p/ link has been found'); //alert('It is entry ... in the array'); //Then edit the entry } } ); } </script> This breaks the contents of the textarea (at spaces) into an array then finds any entries with 'http://instagr.am/p/' in them (could be 'http://instagr.am/p/29fdghHdv'). Once it has found any and all of these entries it will add an '[embed]' code to the beginning and an '[/embed]' tag at the end. Example... http://instagr.am/p/vuHdeyfa2 is converted to: '[embed]http://instagr.am/p/vuHdeyfa2[/embed]' Then the changes must reflected in the textarea input "formname.elements["textareaid"].value = editedstring; Thankyou for your assistance. How can I go about making it so JavaScript will not let a form submit unless a number entered into a field matches a pre-specified number? A guess.. Code: function validateForm() { if (document.forms["form"]["number"].value=="123") { submit} else {alert ("Cant submit because the number doesn't match."); return false; } } I have the following code as shown below: Code: <html> <script type="text/javascript"> var all = []; var a = ["1234", "Jim", "Lab1", "5455"]; var b = ["1235", "Jack", "Lab1", "5459"]; var c = ["1236", "Jane", "Lab1", "5455"]; var d = ["1237", "June", "Lab1", "5458"]; var e = ["1238", "Jill", "Lab2", "5461"]; var f = ["1239", "John", "Lab2", "5462"]; var g = ["1240", "Jacab", "Lab3", "5465"]; all.push(a); all.push(b); all.push(c); all.push(d); all.push(e); all.push(f); all.push(g); for(var i=0; i<all.length; i++){ document.write(all[i] + "<br>"); } </script> </html> How to I get the unique & in order of column 4 given that column 3 is given. Example: If the user provide the value 'Lab1' for column 3, the Javascript will return me the following? Code: "Lab1", "5455" "Lab1", "5458" "Lab1", "5459" In this case, Let's take Google Search as example: The code is JScript .NET, which is basically a .NET version of Javascript. Regardless of language, Anyone with appending type of skill can answer my question. This code is used in Fiddler(It's a Man-in-the-middle proxy) Code: if (oSession.uriContains("&q=")) // oSession is a Fiddler object session // uriContains() function, checks for case-insensitive string from the URI { var str = oSession.fullUrl; var sAppend = "test1+test2+test3"; if (!oSession.uriContains(sAppend)) { oSession.fullUrl = str.replace( "&q=","&q="+sAppend); } } For those who are confused, It says, If &q= is present in the URI, replace/append &q= with &q=test1+test2+test3 Problem: It appends test1+test2+test3 instantly, when it sees &q= in the URL. Basically, how do I make it wait until I click the submit/search button Thank you. Update: I heard about Onsubmit() event, but not really familiar with it. How do I use it? like, should I go to google source page and edit the form id? Also, Any other methods besides Onsubmit()? Hi Everyone! I have a website that I'm designing where I have the need to search multiple sites at specific times. By this I mean that In some cases, we would want to search only the internet using google, or only search the site that I've created (which currently uses the jse_search.js solution), or only our company's website. I currently have four different search boxes that will search either the internet, the internal site, a separate internal site, or a third-party website, which all working fine. The problem is that the search boxes take up quite a bit of space, and the layout is becoming cumbersome. Is there a way in Javascript I could use a single search box and a drop-down list to select which method to use? The code I'm currently using is below. With the exception of the Google search function, I've modified some of the site names to general site names and paths to preserve the company's anonymity: Code in the <head> tag: Code: <script language="JavaScript1.3" type="text/javascript" src="jse_form.js"> </script> Code in the <body> tag: Code: <!--Begin Internal Site Search 1!--> <div> <p style="text-align: center;"> <table border="0" cellpadding="0"> <tr><td><form name="jse_Form" onsubmit="search_form(jse_Form);return false"> <input type="text" name="d" size="30"> </tr></td> <tr><td> <input type="button" value="Internal Site Search 1" onclick="search_form(jse_Form)"> </form> </tr></td> </table> <!--End Internal Site Search 1!--> <!--Begin Internal Site Search 2!--> <div> <p style="text-align: center;"> <table border="0" cellpadding="0"> <tr><td> <!--webbot bot="Search" S-Index="all" S-Fields S-Text="Search for:" I-Size="20" S-Submit="Start Search" S-Clear="Reset" S-TimestampFormat="%m/%d/%Y" TAG="BODY" b-useindexserver="1" startspan --> <form action="http://sitesearch2.idq" method="POST"><input type="text" name="UserRestriction" size="30" value> </tr></td> <tr><td style="text-align: center;"> <input type="submit" value="Internal Site Search 2"></form> </form> <!--webbot bot="Search" i-checksum="4210" endspan --> </td></tr> </table> </div> <!--End Internal Site Search!--> <!--Begin Google Search!--> <form method="get" action="http://www.google.com/search"> <div> <p style="text-align: center;"> <table border="0" cellpadding="0"> <tr><td> <input type="text" name="q" size="30" maxlength="233" value="" /> </tr></td> <tr><td align="center"> <input type="submit" value="Google Search" /></td></tr> </table> </div> </form> <!--End Google Search!--> <!--Begin Third Party Search!--> <form id="keywordSearchForm" method="get" action="http://www.site3.html"> <div> <p style="text-align: center;"> <table border="0" cellpadding="0"> <tr><td> <input class="input" type="text" name="keyword" size="30" /> </tr></td> <tr><td align="center"> <input type="hidden" name="origin" value="keywordsearch" /><input id="go" class="button" tabindex="0" type="submit" value="Third Party Search" /> </td></tr> </table> </div> </form> <!--End Third Party Site Search!--> Hi experts, is it possible via Javascript to search certain websites with certain keywords without having to use specific search engines? example search only the following: 1. www.yyy.com 2. www.aaa.com 3. www.zzz.com for the keyword "Laminat" and open the sites accordingly. thx Hi there, I've got a div with an id of messages - It is essentially a chat system however chat usually adds messages to the bottom of a list which means the messages do not get pushed down while you are reading them. This system instead adds the messages to the top. I need a way of finding the current scroll position so that when a new message is added the scroll remains in the same place. I've been trying to work this out for a while now, any advice or code would be greatly appreciated. Hi, This is my site at the moment in testing: http://whnpf.perdu.servertrust.com/ I have the ideal layout of my slides underneath the actual slide itself. My problem is, everytime I copy the code and place it in again, for some reason the slide goes to the next line and not next to the other slide. Here is my code for the current slide: <script type="text/javascript" src="/v/vspfiles/assets/images/stepcarousel.js"></script> <script type="text/javascript" src="/v/vspfiles/assets/images/stepcarousel.js"> </script> <style type="text/css"> .stepcarousel{ position: relative; /*leave this value alone*/ border: 1px solid GREY; overflow: scroll; /*leave this value alone*/ width: 313px; /*Width of Carousel Viewer itself*/ height: 262px; /*Height should enough to fit largest content's height*/ } .stepcarousel .belt{ position: absolute; /*leave this value alone*/ left: 0; top: 0; } .stepcarousel .panel{ float: left; /*leave this value alone*/ overflow: hidden; /*clip content that go outside dimensions of holding panel DIV*/ margin: 0px; /*margin around each panel*/ width: 313px; /*Width of each panel holding each content. If removed, widths should be individually defined on each content DIV then. */ } </style> <script type="text/javascript"> stepcarousel.setup({ galleryid: 'mygallery', //id of carousel DIV beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs panelclass: 'panel', //class of panel DIVs each holding content autostep: {enable:true, moveby:1, pause:3000}, panelbehavior: {speed:500, wraparound:false, wrapbehavior:'slide', persist:true}, defaultbuttons: {enable: true, moveby: 1, leftnav: ['/v/vspfiles/assets/images/backward.jpg', 80, 215], rightnav: ['/v/vspfiles/assets/images/forward.jpg', -135, 215]}, statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels contenttype: ['inline'] //content setting ['inline'] or ['ajax', 'path_to_external_file'] }) </script> <div id="mygallery" class="stepcarousel"> <div class="belt"> <div class="panel"> <img src="/v/vspfiles/assets/images/HOTDEALS.jpg" /> </div> <div class="panel"> <img src="/v/vspfiles/assets/images/POPULAR.jpg" /> </div> <div class="panel"> <img src="/v/vspfiles/assets/images/HOTDEALS.jpg" /> </div> <div class="panel"> <img src="/v/vspfiles/assets/images/POPULAR.jpg" /> </div> <div class="panel"> <img src="/v/vspfiles/assets/images/HOTDEALS.jpg" /> </div> </div> </div> Any help would be greatly appreciated, thank you I have a mortgage calc that is adding an extra decimal place to my interest rate. To see this in action go to: http://www.keithknowles.com/elmtree/mortgagecalc2.htm Change the interest rate to 7.5 Click Calculate Payment Click Create Amortization Chart On the following screen you'll see a recap of your data and the interest rate will now say 7.55. Same thing happens if you enter 6.2. Next screen shows 6.22/ I've attached the html and js files in a zip. Any help is greatly appreciated. Thanks. Is it possible to place links in a text area box? I tried the below but it doesn't work but how can it be done. Any suggestions? Tracy Code: <textarea rows="2" name="S1" cols="20"> <a href="http://yahoo.com">Yahoo</a><br> <a href="http://google.com">Google</a> </textarea> Hi All, Im currently working on a bidding application built within ASP.Net and i have found this javascript snippet to only allow numeric values in the desired <asp:textbox> which is working fine, but i want to allow the user to add a decimal place. For example, say the bid is 1.50 they should be allowed to enter 1.51 but as i cant imput (.) i end up putting in 151 heres the snippet it may be a slight modification but im new to javascript so any help of knowledge will be highly appreciated Code: function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } thanks in advance Hello! First off, please excuse my ignorance. I am a bit new to the coding world. I want users to be able to enter data into a textbox on my site, and the data then be placed at the end of a specific url, followed by '.html'. For example, say my website is mysite.com. If someone enters in the word "John" in the textbox and clicks the 'Submit' button, the URL should now be: mysite.com/John.html Thanks in advance! I've wrote a jQuery script to fade some lines of text on the page. I've tested it and know it works. I've tried adding it to my WordPress homepage and testing it locally, but it doesn't work, I don't really know what I'm doing, and I can't make heads nor tails of the codex. I'd appreciate either a simple explanation or a real-world example Here are the steps I've taken: 1. added the line <?php wp_enqueue_script("jquery"); ?> just above the wp_head line. 2. added the script just below the wp_head line 3. Used the "No Conflict" syntax of jQuery(document).ready(function() {. Here's what the header looks like where I put my script Code: <?php /** * Template Name: Home Page * * @package WPFramework * @subpackage Template */ ?> <!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" <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo('charset'); ?>" /> <?php if (is_search()) { ?> <meta name="robots" content="noindex, nofollow" /> <?php } ?> <title> <?php if (function_exists('is_tag') && is_tag()) { single_tag_title("Tag Archive for ""); echo '" - '; } elseif (is_archive()) { wp_title(''); echo ' Archive - '; } elseif (is_search()) { echo 'Search for "'.wp_specialchars($s).'" - '; } elseif (!(is_404()) && (is_single()) || (is_page())) { wp_title(''); echo ' - '; } elseif (is_404()) { echo 'Not Found - '; } if (is_home()) { bloginfo('name'); echo ' - '; bloginfo('description'); } else { bloginfo('name'); } if ($paged>1) { echo ' - page '. $paged; } ?> </title> <link rel="shortcut icon" href="/favicon.ico"> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>"> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>"> <?php if ( is_singular() ) wp_enqueue_script('comment-reply'); ?> <?php wp_enqueue_script("jquery"); ?> <?php wp_head(); ?> <script type="text/javascript"> jQuery(document).ready(function() { //set all the divs opacity to 0 $("#rotator div").css({opacity: 0}); //show the current div $("#rotator div.current").css({opacity: 1}); //run the rotateImages function every 3 seconds setInterval("rotateBanners()", 4000); }); function rotateBanners () { var curBanner = $("#rotator div.current"); //get whatever div is after the current banner var nxtBanner = curBanner.next(); //if there's nothing left, go back to top of loop if (nxtBanner.length == 0) nxtBanner = $("#rotator div:first"); curBanner.removeClass('current').addClass("previous").animate({ opacity: 0.0 }, 1500); nxtBanner.css({ opacity: 0.0 }).addClass("current").animate({ opacity: 1.0 }, 1500, function() { curBanner.removeClass("previous"); }); }; </script> </head> Hi, I am creating a webpage to display menu items in a div tag. The premis of my page is to use 4 div tags. 1st div tag = company logo (top left) 2nd div tag = img of restaurant and address (top right). 3rd div tag = horizontal menu with text or buttons to call up menu items, for example: Lunch: Dinner: Beverages: Driving Directions, etc 4th div to display content pages. For example, if the user clicks the Lunch button, it would call the lunch page and place it into the 4th div tag. I am able to do this with frames in HTML or content pages in ASP.net, but how would I do it using CSS and div tags. The best response I got was with AJAX, but I am not familiar with this language yet. Can I use JavaScript to do this? Any suggestions? Thank you, Paul |