JavaScript - Credit Card Matching Regexp
Here's another problem I'm having, I have to validate credit card types. My code worked originally. I simply checked the prefix for each type then verified the length with an if statement. However, I decided to change the code so that only numbers would work after the prefix (as the old code would have allowed any character).
This is the code I have: 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>Credit Card Validation</title> <link rel="stylesheet" type="text/css" href="default.css" /> <script type="text/javascript"> function checkCC(myForm) { var ccType; var ccLength; var ccNum = myForm.cardNum.value; if (myForm.cardType.selectedIndex == 0) { ccType = "Visa"; } else if (myForm.cardType.selectedIndex == 1) { ccType = "MasterCard" } else if (myForm.cardType.selectedIndex == 2) { ccType = "AmericanExpress" } switch(ccType) { case "Visa": { valid = /^4\d{12}(?:\d{3})?$/; if (valid.test(myForm.cardNum.value)) { alert("This is a Valid Visa Card"); return true; } else { alert("This Card Number is Invalid For Visa"); return false; } break; } case "MasterCard": { valid = /^5[1-5]\d{14}$/; if (valid.test(myForm.cardNum.value)) { alert("This is a Valid MasterCard Card"); } else { alert("This Card Number is Invalid For MasterCard"); } break; } case "AmericanExpress": { valid = /^3[47]\d{13}$/; if (valid.test(myForm.cardNum.value)) { alert("This is a Valid American Express Card"); //return true; } else { alert("This Card Number is Invalid For American Express"); //return false; } break; } default: myForm.cardNum.value = null; alert("Card type not found"); return false; } } </script> </head> <body> <h1>Credit Card Validator</h1> <table> <form name="creditCard"> <tr> <td><span class="labels">Card Type:</span></td> <td> <select name="cardType" size="3"> <option name="visa">Visa</option> <option name="mc">Master Card</option> <option name="amex">American Express</option> </select> </td> <tr> <td><span class="labels">Card Number:</span></td> <td><input name="cardNUm" type="text" size=30 value="" /></td> </tr> <tr><td colspan="2"> </td></tr> <tr> <td> <input type="button" value="Death to All" style="background-color:#666666 !important" onclick="return(checkCC(this.form,))" /> </td> </tr> </form> </table> </body> </html> Upon pressing the button nothing happens, I'm completely unsure where I went wrong as all the code seems valid... Please help. Thanks in advance. Similar TutorialsHi all, Im trying to get this working for my Website i have seen alot of Credit Card code both JS and Jquery I have came across one that i really like all the user has to do is enter in his Card Number and it will auto detect what type of card he/she has . Code: <input id="ccNumber" onChange="SetTypeText(this.value)" /> <br /> <div id="cardType"></div> Code: <script type="text/javascript"> function SetTypeText(number) { var typeField = document.getElementById("cardType"); typeField.innerHTML = GetCardType(number); } function GetCardType(number) { var re = new RegExp("^4"); if (number.match(re) != null) return "Visa"; re = new RegExp("^(34|37)"); if (number.match(re) != null) return "American Express"; re = new RegExp("^5[1-5]"); if (number.match(re) != null) return "MasterCard"; re = new RegExp("^6011"); if (number.match(re) != null) return "Discover"; return ""; } </script> But cant seem how i could place in code to see if the card is valid or invalid as alot of the source code out their is using Selection and Arrays.. Does any one know how i could get Validation done with the auto Detect Card code ? Code: cards [0] = {cardName: "Visa", lengths: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {cardName: "MasterCard", lengths: "16", prefixes: "51,52,53,54,55", checkdigit: true}; cards [2] = {cardName: "DinersClub", lengths: "14,16", prefixes: "300,301,302,303,304,305,36,38,55", checkdigit: true}; cards [3] = {cardName: "CarteBlanche", lengths: "14", prefixes: "300,301,302,303,304,305,36,38", checkdigit: true}; cards [4] = {cardName: "AmEx", lengths: "15", prefixes: "34,37", checkdigit: true}; cards [5] = {cardName: "Discover", lengths: "16", prefixes: "6011,650", checkdigit: true}; cards [6] = {cardName: "JCB", lengths: "15,16", prefixes: "3,1800,2131", checkdigit: true}; cards [7] = {cardName: "enRoute", lengths: "15", prefixes: "2014,2149", checkdigit: true}; cards [8] = {cardName: "Solo", lengths: "16,18,19", prefixes: "6334, 6767", checkdigit: true}; cards [9] = {cardName: "Switch", lengths: "16,18,19", prefixes: "4903,4905,4911,4936,564182,633110,6333,6759", checkdigit: true}; cards [10] = {cardName: "Maestro", lengths: "16,18", prefixes: "5020,6", checkdigit: true}; cards [11] = {cardName: "VisaElectron", lengths: "16", prefixes: "417500,4917,4913", checkdigit: true}; var cardType = -1; for (var i=0; i<cards.length; i++) { if (cardName.toLowerCase() == cards[i].cardName.toLowerCase()) { cardType = i; break; } } if (cardType == -1) { return false; } // card type not found value = value.replace (/[\s-]/g, ""); // remove spaces and dashes if (value.length == 0) { return false; } // no length var cardNo = value; var cardexp = /^[0-9]{13,19}$/; if (!cardexp.exec(cardNo)) { return false; } // has chars or wrong length cardNo = cardNo.replace(/\D/g, ""); // strip down to digits if (cards[cardType].checkdigit){ var checksum = 0; var mychar = ""; var j = 1; var calc; for (i = cardNo.length - 1; i >= 0; i--) { calc = Number(cardNo.charAt(i)) * j; if (calc > 9) { checksum = checksum + 1; calc = calc - 10; } checksum = checksum + calc; if (j ==1) {j = 2} else {j = 1}; } if (checksum % 10 != 0) { return false; } // not mod10 } var lengthValid = false; var prefixValid = false; var prefix = new Array (); var lengths = new Array (); prefix = cards[cardType].prefixes.split(","); for (i=0; i<prefix.length; i++) { var exp = new RegExp ("^" + prefix[i]); if (exp.test (cardNo)) prefixValid = true; } if (!prefixValid) { return false; } // invalid prefix lengths = cards[cardType].lengths.split(","); for (j=0; j<lengths.length; j++) { if (cardNo.length == lengths[j]) lengthValid = true; } if (!lengthValid) { return false; } // wrong length return true; }, jQuery.validator.messages.creditcard); Starting off by saying this is directly from a book: Code: <script type="text/javascript"> /* <![CDATA[ */ function validateCard(){ //American Express if(document.forms[0].cardName.value =="American Express"){ var cardProtocol = new RegExp("^3[47][0-9]{13}$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } //Diners Club else if(document.forms[0].cardName.value =="Diners Club"){ var cardProtocol = new RegExp("^3(?:0[0-5]|[68][0-9])[0-9]{11}$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } //Discover else if(document.forms[0].cardName.value =="Discover"){ var cardProtocol = new RegExp("^6(?:011|5[0-9]{2})[0-9]{12}$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } //JCB else if(document.forms[0].cardName.value =="JCB"){ var cardProtocol = new RegExp("^(?:2131|1800|35\d{3})\d{11}$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } //Mastercard else if(document.forms[0].cardName.value =="Mastercard"){ var cardProtocol = new RegExp("^5[1-5][0-9]{14}$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } //Visa else if(document.forms[0].cardName.value =="Visa"){ var cardProtocol = new RegExp("^4[0-9]{12}(?:[0-9]{3})?$"); if(cardProtocol.test(document.forms[0] .cardNumber.value)) document.forms[0].ccResult.value ="Valid credit card number"; else document.forms[0].ccResult.value ="Invalid credit card number"; } } /* ]]> */ </script> With a drop down box for the card type and a text-box to input a credit card number of appropriate length. My question, the teacher asked us to help make this code more "efficient" and I'm still learning the language, and was wondering if a loop could be utilized to make the code more efficient? Switch statement would just repeat the code practically I am tired and fatigued, but I don't believe enough to not find obvious mistakes. I'm having a very strange issue that I have not encounted where a HTML form is submitting when just the first two INPUT's are filled in, but it shouldn't be able to submit because there are still other INPUT boxes that are empty and required to be filled for JavaScript to allow the form to submit. Can anyone see what the problem is? Code: <SCRIPT type="text/javascript"> function validateForm() { if (document.forms["form"]["cardholdername"].value=="") { alert ("Cannot proceed to purchase because a Visa card name has not been specified."); return false; } if (document.forms["form"]["cardnumber"].value=="") { alert ("Cannot proceed to purchase because a Visa card number has not been specified."); return false; } if (document.forms["form"]["cardexpirymonth"].value=="") { alert ("Cannot proceed to purchase because a Visa card expiry month has not been selected."); return false; } if (document.forms["form"]["cardexpiryyear"].value=="") { alert ("Cannot proceed to purchase because a Visa card expiry year has not been selected."); return false; } if (document.forms["form"]["cardcvv"].value=="") { alert ("Cannot proceed to purchase because a Visa card CVV has not been specified."); return false; } if (document.forms["form"]["cardholdere-mailaddress"].value=="") { alert ("Cannot proceed to purchase because a Visa card holder e-mail address has not been specified."); return false; } if (document.forms["form"]["cardholdercontactnumber"].value=="") { alert ("Cannot proceed to purchase because a Visa card holder contact number has not been specified."); return false; } } </SCRIPT> Code: <FORM action="processpaymentinformation.html" method="post" name="form" onsubmit="return validateForm()"> <DIV class="payment"> <DIV class="visacard"><B>Visa card:</B></DIV> <BR> <DIV class="cardholdername"><B>Name:</B> <INPUT name="cardholdername" type="text"></DIV> <DIV class="cardnumber"><B>Number:</B> <INPUT name="cardnumber" type="text"></DIV> <DIV class="cardexpirymonth"><B>Expiry month:</B> <SELECT name="cardexpirymonth"> <OPTION></OPTION> <OPTION>01</OPTION> <OPTION>02</OPTION> <OPTION>03</OPTION> <OPTION>04</OPTION> <OPTION>05</OPTION> <OPTION>06</OPTION> <OPTION>07</OPTION> <OPTION>08</OPTION> <OPTION>09</OPTION> <OPTION>10</OPTION> <OPTION>11</OPTION> <OPTION>12</OPTION> </SELECT> </DIV> <DIV class="cardexpiryyear"><B>Expiry year:</B> <SELECT name="cardexpirymonth"> <OPTION></OPTION> <OPTION>13</OPTION> <OPTION>14</OPTION> <OPTION>15</OPTION> <OPTION>16</OPTION> <OPTION>17</OPTION> </SELECT> </DIV> <DIV class="cardcvv"><B>CVV:</B> <INPUT class="cardcvv" name="cardcvv" type="password"></DIV> <BR> <BR> <DIV class="visacardholder"><B>Visa card holder:</B></DIV> <BR> <DIV class="cardholdertitle"><B>Title:</B> <SELECT name="cardholdertitle"> <OPTION></OPTION> <OPTION>Dr</OPTION> <OPTION>Madam</OPTION> <OPTION>Miss</OPTION> <OPTION>Mr</OPTION> <OPTION>Mrs</OPTION> <OPTION>Ms</OPTION> <OPTION>Sir</OPTION> </SELECT> </DIV> <DIV class="cardholdere-mailaddress"><B>E-mail address:</B> <INPUT name="cardholdere-mailaddress" type="text"></DIV> <B>Contact number:</B> <INPUT name="cardholdercontactnumber" type="text"> </DIV> <DIV> <INPUT class="submit" type="submit" value="PROCEED TO PURCHASE"> </DIV> </FORM> I have an autocomplete script but it's currently returning results in a character is in the name anywhere at all, what I need it to do is only return matches if the characters are in sequence only. Example of how it is now if you type S it will return: Science Host Pass What I need it to do is only return a match if the first character is an S, and so on down the line in order. So if you type sam it should only return matches where the first 3 letter are sam in the order it's typed. Here's how the regexp is now: return value.replace(new RegExp("(?![^&;]+(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+", "gi"), "<strong>$1</strong>"); I would like help because I cannot find the error in my code. js code Code: function luhnCheckSum(sCardNum) { var iOddSum = 0; var iEvenSum = 0; var bIsOdd = true; for (var i=sCardNum.length-1; i >= 0; i--) { var iNum = parseInt(sCardNum.charAt(i)); if (bIsOdd) { iOddSum += iNum; } else { iNum = iNum * 2; if (iNum > 9) { iNum = eval(iNum.toString().split("").join("+")); } iEvenSum += iNum; } bIsOdd = !bIsOdd; } return ((iEvenSum + iOddSum) % 10 == 0); } function isValidVisa(sText) { var reVisa = /^(4\d{12}(?:\d{3})?)$/; if (reVisa.test(sText)) { alert("Please enter a Card Number."); clock.CardNumber.focus(); return luhnCheckSum(RegExp.$1); } else { alert("This card number is not valid."); return false; } } html Code: <input type="text" size="16" name="Card_Number" onmouseout="isValidVisa(this)"/> Hi there, basically i have created a simple card game, i have one html page with 6 decks of cards. The decks are just images that when clicked display 6 other cards on another html page. What i want to do is that when i click a card on the second page i want the card to be removed, so that when i go back the first page and select the same deck again, the second page opens and the card i had selected before is still removed? Is this possible with javascript please i am totally new to it. Please could someone give me some direction? Thanks
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. 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!!!!!!!!! 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 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? 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! Hey. I am looking for a gallery/image slider script that looking like this image/or does the same as the image below: Something like that or similar if anyone knows a link to one or knows the code please help. Thanks for reading. Mark. 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 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 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> 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 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... I have a situation where there is a string: m0|18:+:m1|(-3) which is a tracking method for preserving memory references in the following string: 18+(-3) In the user interface of the project I am working on; the user changes the string to: (18+(-3))*8 The object is to revise the memory tracking string to repersent the changes. should be: (m0|18+m1|(-3))*8 Code: //matches = this.getMemVals() // getMemVals() searches the string 'm0|18:+:m1|(-3)' // with regex pattern to find instances of m#|# var matches = new Array() matches[0] = 'm0|18'; matches[1] = 'm1|(-3)'; var currentStateSaved = '(18+(-3))*8'; var glbs = ''; for(i = 0; i < matches.length; i++) { var matRegex = new RegExp(matches[i].substring(matches[i].indexOf('|')+1), 'g'); alert('matReg: '+matRegex); glbs = currentStateSaved.replace(matRegex, matches[i]); } alert('GLBS: '+glbs) // <<< test code The '18' part of m0|18 is not be found in the revised literal string Why? (Has '18' been coverted to a number datatype?) This is the type of problem that drives me up a wall and cost far to much time trying to flush it out Thanks of suggestions, advice JK 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]+)\/?(.*)/ 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! |