JavaScript - Indexof Or Regexp?
Hello there
I'm trying to build a simple little bot that you can ask questions. I'm using the indexOf method but I'm not sure if this is the best option for what I'm trying to do. If you type 'hello' or 'how are you' it answers. Any other input results in 'Dreadfully sorry but I didn't catch that. Say again?'. Is there a way that I can search input for certain words or combinations of words and trigger a single answer? Any help appreciated. <!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>Bot</title> <script type="text/javascript"> function bot(go){var a = go.getElementsByTagName('input');var q = a[0];var t = q.value.toLowerCase();document.go.reset();if(t.indexOf('hello')!=-1){document.getElementById('bot').innerHTML = "Hello to you.";return false;}if(t.indexOf('how are you')!=-1){document.getElementById('bot').innerHTML = "I am functioning within acceptable parameters, thank you.";return false;};go.action=document.getElementById('bot').innerHTML = "Dreadfully sorry but I didn't catch that. Say again?"; return false;}; </SCRIPT> </head> <body onLoad="document.go.q.focus()"> <div align="center"> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <form name="go" onsubmit='return bot(go)' id="go" action=""><input name='q' type='text' /><input name='' type='hidden' /></form> <p> </p><div id="bot" align="center"></div> </div> </body> Similar TutorialsHi, I am trying to build a bookmarklet to use on the swiss legislation website. All the pages are available in several languages and I want to be able to switch with one button from french to german and from german to french. As an example, the URLs are as follow for the same page: in French: http://www.admin.ch/ch/f/rs/311_0/index2.html in German: http://www.admin.ch/ch/d/sr/311_0/index2.html So I built quite easily two bookmarklets to switch FR-DE and DE-FR: Code: javascript: var str = window.location.pathname;str = str.replace("f/rs", "d/sr");window.location = str; Code: javascript: var str = window.location.pathname;str = str.replace("d/sr", "f/rs");window.location = str; But when I try to get a single script by using if/else, I cannot manage to have the "else" part working: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { str = str.replace("d/sr", "f/rs"); window.location = str; } Thinking it might have to do with str.replace, I tried an easier variant, but even this one does not work, the "else" part is never called: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { alert('no'); }; I would appreciate any help on the matter... thanks in advance, RJ This is a snippet from a project I'm working on involving XML DOM, but the question is really about javascript. This is the problematic code. Code: else if (nodeOccurance.IndexOf('each:') == 0) { . . . } I want the if statement to be true if the value of the variable "nodeOccurance" begins with "each:" For some reason, it's just stopping my whole script and doing nothing. Any help? Thanks, Julian Hi, I'm trying to match a text string within a textarea node and then use a text range to set the users cursor highlighting over the word.My code for this is as follows: Code: function doHighlight(theWord, textAreaElement) { var text = textAreaElement.value; var theIndex = text.indexOf(theWord); setCaretPos(textAreaElement, theIndex, theIndex+theWord.length); } function setCaretPos(obj, start, end) { var range = obj.createTextRange(); range.moveStart('character', start); range.moveEnd('character', end - obj.value.length); range.select(); } I have a text area with the following html: Code: <TEXTAREA>blah blah sausage Frank Jones</TEXTAREA> (ie there are four lines visible to the user, the 3rd is blank). And I call the doHighlight method with 'blah blah', 'sausage' and 'frank jones' respectively. However the highlighting isnt working quite right - when I try to highlight 'blah blah', it highlights 'blah bl', when I try to highlight 'sausage' it highlights 'ausa' (the 2nd-5th characters) and when I try to highlight 'frank jones', it highlights 'nk jones'. This code seems to work fine when there is only a single line of text in the text area though - so I'm guess it's something to do with newline characters. Can anybody point me in the right direction as to how to fix this bug please? Thanks. 0 down vote favorite share [g+] share [fb] share [tw] I have a fairly large program that I have simplified to show the problem that I am having. I have 2 div's under which I have an image and some text. When I hover on the image, the jQuery hover over image event fires. Through all this, I am able to get the Id's of both the images & their parent div's. However, when I try to get the index value of the Id's in an array, it always returns -1 ie... not found. Can you please help. The code is enclosed below. I am new to javascript & jQuery and hence the need of some help. Maybe the solution is very trivial. Thanks in advance. Regards, sbguy <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var input_array = new Array("input1_Id", "input2_Id"); var div_array = new Array("div1_Id", "div2_Id"); window.onload=function(){ jQuery.ready(); img_hover_event_handler(); } //________________________________________________ function img_hover_event_handler() { var input_id = ""; var div_id = ""; var input_index, div_index; $("input.Lrollover").hover( function() { input_id = new String(this.id); input_index = new String(input_array.indexOf(div_id)); div_id = new String($(this).closest('div').attr('id')); // id of the parent div div_index = new String(div_array.indexOf(div_id)); alert(input_id + ", " + input_index + ", " + div_id + ", " + div_index); }, function() { }); } </script> </head> <body> <div id="div1_Id"> <input class="Lrollover" id="input1_Id" type="image" src="images/LGbtn_off.png" alt="Image1" /> <p id="myp1_Id">"Hello World 1"</p> </div> <br><br><br> <div id="div2_Id"> <input class="Lrollover" id="input2_Id" type="image" src="images/LGbtn_off.png" alt="Image2"/> <p id="myp2_Id">Hello World 2"</p> </div> </body> </html> hi all, my indexof() function is not being recognized when I enter an email address for an unsubscribe form I have on one of my pages. Additionally, the confirmation message is also not showing up when the email address IS valid. Here is my code that I am using on a PHP page: PHP Code: function Unsubscribe() { var IsValid = document.getElementById("email").value; alert(IsValid.indexOf("@")); exit; if (document.getElementById("email").value.length == 0 || IsValid.indexOf("@")) == -1) { alert("Enter a valid email address"); exit; } else { <?php $handle = @fopen("../logs/unsubscribes.txt", "a"); fputs($handle, $_POST["email"] . " " . "\r\n"); fclose ($handle); ?> alert(IsValid &&" has been unsubscribed."); <?php if (! $_POST["email"]) { //DO NOTHING } else { header("Location: http://www.google.com/"); } ?> } } //--> </script> </head> <body> <form action="" method="post" name="frm" onsubmit="Unsubscribe()"> <center><br /> Enter Your Email Address:<br /> <input type="text" id="email" name="email" /> </center> <p> <label> <center><input type="submit" id="unsubscribe" value="Unsubscribe Me" /></center> </label> </p> </form> </body> </html> to those PHP experts, I am aware of the RegEx function for validation, but I don't understand it, which is why I don't use it (in case anyone points that out). The other thing that is problematic is that the PHP code is automatically using HEADER() regardless of "email"'s value Hi there! OK I need a little help as I'm not sure how to integrate this function into my form. First of all I should explain that my form doubles as a Google Search box. If you select the Google Search radio button it submits the input text to Google. It also defaults to Google if anything else other than "red", "green" or "blue" are entered. Now what I'd like to do is add a function so that if someone enters "purple is my favorite color" it recognizes the "purple" part of the string using something like .indexOf('purple'); and calls something like if(function==-1) { theForm.action = "Other choice "+ q.value; . How can I add this to my form? Thank you for any help. My form code: Code: <script> function convert(theForm){ var els = theForm.getElementsByTagName('input');// store inputs var q = els[0], color = els[1]; if(els[4].checked){// submit to google theForm.action = 'http://www.google.com/search'; return true; }; color.value = "Chosen "+ q.value +" color"; switch(q.value){// check the query case 'red': case 'green': case 'blue': location.href = color.value; return false; break; default: theForm.action="http://www.google.com/search"; break; }; return true; }; </script> <form name= "myform" onsubmit='return convert(this)'> <input name='q' type='text' /> <input name='color' type='hidden' /> <input type='submit' value=" Enter " /> <br /> <input name="searchType" type="radio" value="" checked="checked" > <label for="all"> My Form </label> <input name="searchType" type="radio" value="google" onclick="document.myform.action='http://www.google.com/search';" /> <label for="google"> Google Search </label></form> Hello @all readers, i'm trying to extract some text out of an options-selectmenu. The text of these option menus are pulled out of a webdb. For each option there excist a main value,for each main value, there excist an aditional price,either a minus (-) or a plus (+) to the main price: main item: graphiccard price 200,- options: 16 Mb (- 10) 32 Mb (main price,no need to get aditional value) 64 Mb (+ 50) 128 Mb (+ 100) So if user choose 128 MB (+ 100) i require a var that say's : 128 MB a var that say's: + a var that say's : 100 All selected options could contain many variants, it isnt pinned to the sample above,however,all options are formatted like this: someTextAndMabyNumbers_1 (aPlusOrMinusSign_2 AlwaysaNumber_3) I would apreciate to get a solution to this problem. I am not programming for living,the end result is for community.(oscommerce) To see a live version , ask me for the url (incase of seen as spam i not post until aprovement) Here is the code i pull out from the selectmenu,all alternative methodes instead of using regexp are much welcome. Code when clicked submit button and the regexp result var comes: Code: $("#submitme").live('click', function() { var mystringId = prodID; var addedOn = new Date(); $('select').each(function() { var selectId= $(this).attr("id"); var selectedOption = $(this).find('option:selected'); var selectedOptionValue = selectedOption.val(); mystringId += '{' + selectId + '}' + selectedOptionValue; }); db.transaction(function(tx) { tx.executeSql('SELECT COUNT(*) AS total FROM customers_basket WHERE products_unique_id ="'+ mystringId +'"', [], function (tx, results) { total = results.rows.item(0)['total']; if (total == 0){ $('select').each(function() { var selectName= $(this).attr("name"); var selectId= $(this).attr("id"); var selectedOption = $(this).find('option:selected'); var selectedOptionValue = selectedOption.val(); var selectedOptionText = selectedOption.text(); db.transaction(function(tx) { tx.executeSql('INSERT INTO customers_basket_attributes (customers_id, products_id, products_unique_id, customers_basket_quantity, products_options_id, products_options_txt, products_options_value_id, products_options_value_txt) values ("1" , "'+prodID+'" , "'+mystringId+'" ,"1", "'+selectId+'" , "'+selectName+'" , "'+selectedOptionValue+'" , "'+selectedOptionText+'")'); }); }); db.transaction(function(tx) { tx.executeSql('INSERT INTO customers_basket (customers_id, products_id, products_unique_id, customers_basket_quantity, final_price, customers_basket_date_added) values ("1" , "'+prodID+'" , "'+mystringId+'" , "1" , "0" , "'+addedOn+'")'); }); }else{ tx.executeSql('UPDATE customers_basket SET customers_basket_quantity = customers_basket_quantity + 1 WHERE products_unique_id ="'+ mystringId +'"'); tx.executeSql('UPDATE customers_basket_attributes SET customers_basket_quantity = customers_basket_quantity + 1 WHERE products_unique_id ="'+ mystringId +'"'); } }); }); $('.ui-dialog').dialog('close'); }); Code where the option selectmenu is generated: option.text(val+ ' (' +prefix+ ' ' +price+ ') '); representing the required regexp / alternativecode Code: for(key in products_options_array) { var value=products_options_array[key]; prodOpId = value['products_options_id']; prodOpName = value['products_options_name']; prodOpValueId = value['products_options_values_id']; prodOpValueName = value['products_options_values_name']; prodOpValuePrice = value['options_values_price']; prodOpValuePrefix = value['price_prefix']; var arr = [ { optionname: prodOpName, optionvalue: prodOpValueName, optionnameid: prodOpId, optionvalueprice: prodOpValuePrice, optionvaluepriceprefix: prodOpValuePrefix, } ]; for (var i = 0; i < arr.length; i++) { var r = arr[i]; //console.log(r); name = r.optionname; val = r.optionvalue; nameid = r.optionnameid; valueid = r.optionvalueid; price = r.optionvalueprice; prefix = r.optionvaluepriceprefix; if ($("#prodAttributes_"+prodID+" select").is("[name*=" + name + "]")) { var select = $("#prodAttributes_"+prodID).find("select[name*=" + name + "]"); var option = $("<option>"); option.val(valueid); if (price == 0){ option.text(val); }else{ option.text(val+ ' (' +prefix+ ' ' +price+ ') '); } select.append(option); } else { var select = $("<select>"); select.attr("name", name); select.attr("id", nameid); var option = $("<option>"); option.val(valueid); if (price == 0){ option.text(val); }else{ option.text(val+ ' (' +prefix+ ' ' +price+ ') '); } select.append(option); var label = $("<label>"); label.attr("class", "select"); label.attr("for", name); label.text(name); fieldset.append(select); myform.append(div); $(myform).appendTo("#prodAttributes_"+prodID); } } } myform.append(myinput); myform.trigger('create'); Thank you verry much!!!!!!!!! I would like to perform a regular expression on a string and if TRUE do something. I have huge amounts of knowledge doing this in PHP but trying out javascript. Much appreciated. Hi all, I am having trouble understanding how to get RegExp to work. I've read so many tutorials but none have been clear. They all just explain the patterns you can check for but not how to piece them together! I am trying to write a RegExp pattern that checks an email address so that it allows the characters a-zA-z0-9_ before and after the @ How would I go about doing this? I tried Code: new RegExp("[a-zA-z0-9_].+@[a-zA-z0-9_].+"); but that didnt work. I appreciate any help I was wondering if anyone could help me with regexp: 1)I would like it so that both a first and last name can be entered and that both ' and - can be included 2)I would like it so that addresses have to start with a number and then each word afterwards has to start with a capital letter and can include full stops, ' and - Any help is appreciated! I am using in script http://www.vicsjavascripts.org.uk/Wo...ordToolTip.htm Code: for (;z0<wary.length;z0++){ reg=new RegExp('\\b'+wary[z0][0]+'\\b','g'); html=html.replace(reg,'<a>'+wary[z0][0]+'</a>'); } html=html.replace(/zxc/g,'<'); I expected to be able to use Code: for (;z0<wary.length;z0++){ reg=new RegExp('\\b'+wary[z0][0]+'\\b','gi'); html=html.replace(reg,'<a>$1</a>'); } html=html.replace(/zxc/g,'<'); where $1 = the replaced text can someone please explain? Code: <html> <head> <script> function testemail(){ var fld= document.getElementById("input1").value; var reg = /^[\w+]@[\w+].com$/i; if(reg.test(fld)) { alert("email is ok"); } else { alert("email is not correct"); } } </script> </head> <body> <p> <form name="form1" onsubmit="testemail()"> enter email : <input id="input1" type="text" /> <input id="input2" type="submit" value="Submit" /> </form> </p> </body> </html> I am trying to test an email ID with above RegExp. I enter a correct email or not, I am always getting message "email is not correct" So RegExp is not working. How can I find out whats wrong with this RegExp ? Is there any tool to figure that out ? I tried with FireBug, but it does not point to whats wrong with RegExp Thanks I have been testing regex test string to match the following pattern (- <any number with/without . decimal point>) ( -[#[.#]] ) here is the code that works the best: Code: var testStr = '99999+((-25.533) - 5)/99*(-25.533)'; var negValTestStr = new RegExp('\\(\-{1}[0-9]*\.?[0-9]*\\)', 'g'); var test = testStr.match(negValTestStr) alert(test); The question is: Why does it only work when the open and close parenthesis are double escaped: '\\(' and '\\)' When I use one backslash to escape, it will find -25.533, -5 and -25.533 With two backslashes for escape sequence: (-25.533), (-25.533) Also, I have to escape the - to get just one -. If I do not escape the -, -?; which should read - {0, 1} will match --# without escaping - Thanks for thoughts on this JK hello all I am working on a keyword filter and am stuck on something that I am hoping someone has more experience with my problem is that I am trying to pass a regular expression as a variable to the RegExp() function in javascript but it does not seem to be working example below Code: var X = '^(?=.*?('; var Y = 'dog))(?=.*?(cat))(?=.*?(mouse'; // this gets created dynamically var Z = ')).*$'; var A = X + Y + Z; // result is ^(?=.*?(dog))(?=.*?(cat))(?=.*?(mouse)).*$ and is a valid and tested expression var B = new RegExp(A, 'i'); I want to pass B to a search() function but it does not seem to be accepted as a valid expression anymore thanks for any help I have this string: this is my test <a href="yay.html">yay</a> and want to just match the part before the <a...: this is my test I can't figure out the regular expression for this. I've tried everything I can think of. It seems that it needs to do a non-greedy search on the first < it finds, but nothing works, like: ((.*<)?) Please help, thanks! Hey there, I'm looking to have some functionality similar to Twitter in that pages are loaded through ajax depending on the path that is shown in the URI hash. For example: http://twitter.com/#!/BarackObama/following I could just split the string by "/" but I want it to work if you enter a bunch of forward slashes as well, or none at all (only for the first forward slash), here's an example: http://twitter.com/#///////////BarackObama/following http://twitter.com/#BarackObama/following http://twitter.com/#/BarackObama The hash would be broken down into multiple parts, the first parameter (ie. BarackObama) would be the first returned value from the match, the second would be the rest of the parameters. Here are examples of what the hash would be, and what I would like in return. Hash: 1. http://twitter.com/#/BarackObama/following/test 2. http://twitter.com/#///////////BarackObama/following 3. http://twitter.com/#BarackObama Returned value from RegExp match: 1. BarackObama,following/test 2. BarackObama,following 3. BarackObama Hope that makes it pretty clear. I also have this so far, but it returns both a comma separated list, but also the original string. Code: /([0-9A-z]+)\/?(.*)/ Hey guys, What is wrong with the following regular expression: Code: <script language="javascript" type="text/javascript"> document.write('\\Green Apple\\u003c\\\/a>'.match(/(.*)\\\\u003c\\\\\\\/a>/)); </script> The ouput is: null I am escaping each backlash but it doesnt seem to be working... Hi all, I am having some troule with searching a string taken from a text field (a name textfield, it's basically a form and the script is validating it). I've been on the W3C schools website and I cannot get it to work, even with the "try it" feature. Please help. Code: function nameValidator(entry, msg) { var regExp = new RegExp("[a-z ]", "g"); var s_regExp = new RegExp("[ ]"); var tub = entry.value; var newLength = parseInt(tub.length); var i = 0; var space = 0; if (tub == "" || newLength > 20) { alert(msg + "entry must be > 1 and < 20 characters only!"); return false; } else if (tub.match(regExp)) { for (i=0; i < newLength; i++) { if (tub.substr(i,1) == "") { space += 1; } } if (space < 1) { alert(popup + "you must enter a space.") return false; } if (space > 1) { alert(msg + "you cannot enter a space more than once."); return false; } if (tub.substr(0,1) == s_regExp || tub.substr(newLength,1) == s_regExp) { alert(popup + "the first and last characters cannot be whitespace."); return false; } } return true; } 1. Specifically, it will not correctly evaluate the statement where I've used the s_regExp variable nor will it detect white space at the space counter so it never increases (which the rest of the code relies on!). 2. What am I doing wrong. W3C states just also to use var newvar = new RegExp("\s") but that doesn't work, and I have even tried var newvar = new RegExp("^([a-z ])*$", "g") and that's useless too. how about getting the attributes of the a tag? href and title and the innerhtml (actually the innerhtml has space on both ends)
Hello, I have a the following text that I got from a getElementById and innerHTML and I need to get the model name from this text. Code: <div class="widgetWrap"> <div class="group1"> <h3><span>2010 Ford Escape XLT</span></h3> <dl id="vPrice"> <dt>2010 Ford Escape XLT Prices</dt> The last line has the year make model and trim level, I need to be able to get the model, "Escape" from here. The problem is the model does change, and I need to get whatever the model says, Focus, Expedition and so on. The make may change also, Lincoln or Mercury. Is there an easy way to get just the model name whatever it may be? I have been working on this for a while, and just can't get it. Thanks for your help Marc Damon |