JavaScript - Regular Expressions - Constructing From Strings
Hello everyone,
I'm new to using regular expressions with javascript. I'm trying to search a string for instances of a substring with a particular prefix, followed by some numerical digits. So for instance my larger_string is: "This is a string ABCD12 EFGH124 ABCD76 EFGH90" And initially I want to find all substrings starting 'ABCD', with two following numerical digits. I can do it like this: var answer = larger_string.match(/ABCD\d\d/); But I'd really like to pass the 'ABCD' part in as a string itself, myString, as I'd then like to set myString to 'EFGH' and others, to repeat the search for those. I'm struggling with the syntax for creating a regular expression froma string. So I can do this: var reg = new RegExp("ABCD", "g"); but, this doesn't work: var reg = new RegExp("ABCD\d\d", "g"); and similarly I can do this: var myString = "ABCD"; var reg = new RegExp(myString, "g"); but, this doesn't work: var myString = "ABCD\d\d"; var reg = new RegExp(myString, "g"); What is it that I'm doing wrong here? Thank you Similar TutorialsHello. So I have been doing some regex in php. In Javascript i need to parse a url and replace ALL the & with \/%26 (or what ever that one is) and replace ALL the + with the % thingy. But my problem is I am doing url.replace(/&/,'\/%26') but what is happening is it is replace only the FIRST &. How can I do it to replace ALL &? I was thinking of doing some type of loop but for some reason nothing is working...THANKS IN ADVANCE! Hi everyone, I am trying to validate a date by using regular expressions. I have parts working, such as only accepts numbers, but I cannot get the range correct. On the "mm" field, I am getting errors. Code: if(form.mm.value=="") { alert("Please insert your birth month"); return false;} var re=/^(0[1-9]|1[0-2]){2}$/; if(!re.test(form.mm.value)) { alert("Please fix birth month!"); return false; } { if(form.dd.value=="") { alert("Please insert your birth day"); return false;} var re=/^\d{2}$/; if(!re.test(form.dd.value)) { alert("Please fix birth day!"); return false; } { if(form.yyyy.value=="") { alert("Please insert your birth year"); return false;} var re=/^\d{4}$/; if(!re.test(form.yyyy.value)) { alert("Please fix birth year!"); return false; Any suggestions will be greatly appreciated. How can I get price from a string using regular expression ? Or by any other means . Let's say. var str="Our shop receives only $. This shoe costs $200. We don't accept anything else then $"; How could I retrieve '$200' from this above string. By any means. Thank you... Dear Experts I have folloiwng codes Code: <html> <head> <body> <center> <script language="JavaScript"> function checkpostal(){ var re=/^\D{A-Z}$/ if (myform.myinput.value.search(re)==-1) { alert("Good") }else{ alert("Bad") } } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> </center> </body> </html> With Onclick, I want to test input through regular expression If entered values is between a-z or A-Z then it must display alert("Good") else alert("Bad") Please help Can someone please explain the following code to me!? I don't get regular expressions and how they work :S Code: function trim(string){ return string.replace(/^\s*/, "").replace(/\s*$/, ""); } Thanks! Hey everyone I am trying to match an email string that ends exactly with ".com". Here's what I have Code: var email = window.prompt("Enter your email", ""); var email_match = /[a-zA-Z1-9-_.]{3,}\@[a-zA-Z]{3,}\.(com)/ if (email_match.test(email)) alert("Email is Valid"); else alert("Email Invalid!"); the (com) also matches commm for some odd reason. What must I change in the code so that only emails ending with .com is valid? Thanks! Hi I've got two examples of using regular expressions one works and the other doesn't but they using exactly the same pattern and the same text only difference is - The example that works uses a form to get the patern and text, the other has the pattern hard coded. Any help will be greatly appreciated Works - Code: <html> <head> <title></title> <style type="text/css"> </style> <script type="text/javascript"> <!-- function frmTestClick() { var re = new RegExp(document.frmTest.regex.value,"gi"); if (document.frmTest.subject.value.match(re)) { alert("Successful match"); } else { alert("No match"); } } function demoShowMatchClick() { var re = new RegExp(document.frmTest.regex.value,"gi"); var m = re.exec(document.frmTest.subject.value); if (m == null) { alert("No match"); } else { var s = "Match at position " + m.index + ":\n"; for (i = 0; i < m.length; i++) { s = s + m[i] + "\n"; } alert(s); } } function demoReplaceClick() { var re = new RegExp(document.frmTest.regex.value, "gi"); document.frmTest.result.value = document.frmTest.subject.value.replace(re, document.frmTest.replacement.value); } //--> </script> </head> <body> <div id="content"> <form name="frmTest" id="frmTest" action="" method="post"> <p>Regexp: <input type="text" name="regex" value="</?(b|strong|font|span)\b(.|\n)*?>" size="50"></p> <p>Subject string: <input type="text" name="subject" value="<font>the quick brown fox jumped over <span>the</span> lazy dog</font>" size="50"></p> <p><input type="button" value="Test Match" onclick="frmTestClick()"> <input type="button" value="Show Match" onclick="demoShowMatchClick()"></p> <p>Replacement text: <input type="text" name="replacement" value="replaced" size="50"></p> <p>Result: <input type="text" name="result" value="click the button to see the result" size="50"></p> <p><input type="button" value="Replace" onclick="demoReplaceClick()"></p> </form> </div> </body> </html> Doesn't work??? Code: <html> <head> <title></title> <style type="text/css"> </style> <script type="text/javascript"> <!-- function stripHTML(sVal,bIgnoreBold){ var sPat="</?(b|strong|font|span)\b(.|\n)*?>",re = new RegExp(sPat,"gi"); if (sVal.match(re)) { alert("Successful match"); } else { alert("No match"); } return sVal.replace(re,""); } //--> </script> </head> <body> <div id="content"> <form name="frmTest" id="frmTest" action="" method="post"> <label>Body: </label><textarea name="txtBody" id="txtBody" rows="10" cols="60"><font>the quick brown fox jumped over <span>the</span> lazy dog</font></textarea><br><br> <input type="button" name="btnDoStrip" id="btnDoStrip" value="Do Strip" onclick="this.form.txtBody.value=stripHTML(this.form.txtBody.value,true);"> <input type="reset" name="btnReset" id="btnReset" value="Reset"> </form> </div> </body> </html> Cheers Al Hi All I need help with javascript regular expressions. I have a text box in which user can enter only 4 types of values. 1) Varchar(n) where 0 < n <=80. Ex: Varchar(20) (Varchar(n) . 0< n<= 80 means he can enter values onlly like varchar(1) or varchar(2) ..... varchar(80) ) 2) Char(n) where 0 < n <=80. Ex: Char(20) 3) numeric(x,y) where x>y and 1<= x <=35 and 0<= y <=15. Ex: numeric(20,6) If the text box value doesnot match this pattern, we should throw him alert message. Thanks in Advance Hi, i'm new to javascript, im managing to find out how to do most things, but i need to validate two paths. I want to know how to check whether path1 is a subpath of path2. e.g. 1: /files/stuff/mypics/anotherfolder/etc 2:/files/stuff/mypics i want to be able to return a boolean given whether i can move folder 1 in to folder 2 in this case yes. but if you swap them its a no. please help. oxide Hi wise javascript gurus, I am working on a small form that on the click of a button, it calls a function to validate a string that consists of 3 portions delimited with a dash("-") in the following format XXX-NNNN-XXX where X are letters only where N are numbers only I have to use regular expressions to validate the first portion and verify that its exactly 3 characters long that are letters only if the first portion or "plant code" is larger then 3 characters long an alert gets display also if the first portion contains alphanumeric or numeric characters an alert gets displayed, the first portion has to be in letters only. down below is my code that is not functional at the time because I know for sure the way I check for regular expressions is a bet washy but thats the only thing I was able to come up with, any help will be appreciated. thanks for making time to read my thread Code: <html> <head> <script type="text/javascript"> function validateit() { var number = document.myform.product_number.value; var charnum = number.length; if (number =="") alert("you must enter a product number, field cannot be empty"); else if (charnum < 12 || charnum > 12) alert("the product numbre has to be exactly 12 characters long"); else validate_number(number); } function validate_number(num) { var objRegEx = /^[a-z]+$/; split=num.split("-",3); if (split[0].length!=3) alert("the Plant Code portion of the Product Number has to be only three charactes long") if!(objRegEx.test(split[0]) alert("the Plant Code portion of the Product Number has to be letters only") } </script> <title>waldo's</title> <style type="text/css"> .heading{font-weigth:bold;text-align:center; font-family:"comic sans MS"} </style> </head> <body><form name="myform"> <table align="center" border="1" width="55%"> <caption style="font-family:'comic sans MS';font-size:26pt"> Waldos's WareHouse</caption> <tr class="heading"><td>Product Number</td><td>Plant Code</td><td>Production Run</td><td>Shift Number</td></tr> <tr><td><input type="text" name="product_number"></td><td><input type="text" name="plant_code" readonly></td><td><input type="text" name="production_run" readonly></td><td><input type="text" name="shift" readonly></td></tr> <tr><td><input type="button" value="Check Validity" onclick="validateit()"/></td><td align="right">Validation Date:</td><td colspan="2"><input type"text" size="47" readonly></td></tr> </table></form> </body> </html> Hey I'm trying to make a script which will check if the string which the user sent from a form contains ONLY letters. The problem is if the user entered something like this "25 years old" it allow that to be submitted. It only blocks submissions of the form if the user submits NO letters like this "12345". I want it to block submissions if at least one character isn't a letter. Here's my code: Code: var message = document.myform.formtest.value; var allowed = /[A-z+]/; if(!allowed.test(message)) { alert("The field only allows letters (a-z)."); return false; } Hi I have finally figured how to search a text area for URL's... as below, then reformat so they are clickable links. It works!! But it looks so so messy, is there a better way to do this?? Code: var textNodeLinks = document.getElementById("comments"); textNodeLinks.innerHTML = textNodeLinks.innerHTML.replace(/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/g, "$1<a href=http://$2$3\ rel="nofollow" target=_blank>$2$3</a>"); textNodeLinks.innerHTML = textNodeLinks.innerHTML.replace(/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/g, "$1$2<a href=\"$3\" rel="nofollow" target=_blank>$3</a>"); Cheers I have a string of code like such: Code: <font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>000000000000000000000000000000000000000000000</font><font color=white>0000</font><font color=black>000000000000000000000000000000000000000000000</font><br><font color=black>000000000000000000000000000000000000</font> except much longer, like... 4000 lines longer. What I want to do is go through this code and replace all the zeros between <font color=black> and </font> with 1's and leave anything between <font color=white> and </font> as 0's. I just really need the regular expression not the code. I started reading a book on regular expressions and it's like... 300 pages, so it would be nice to solve this problem now, rather than have to wait to finish the book to solve this. Hopefully when I'm done reading it will make sense, but can someone help me in the meantime? Hi I am trying to create a while loop and I am having trouble with what to put in it so far I have: Code: function showSports(obj) { var groupId=obj.id.substring(0, 1); var indx=obj.id.substring(obj.id.indexOf('_')+1); var id=indx.substring(0, indx.length+1); var displayInfo = false; while (displayInfoTab) { if (indx == 1) { show ('footballInfo'); hide('soccerInfo'); hide('baseballInfo'); } if(indx == 2 ) { show( 'soccerdInfo'); hide('baseballInfo'); hide('footballInfo'); } if(indx == 3 ) { show( 'baseballInfo'); hide('footballInfo'); hide('soccerdInfo'); } displayInfo = true; } } It is supposed to be able to loop through the links below and show/hide depending on which link is selected. Code: <a id='1link_1a' title="football Tab" onclick='showSports(this);'><span >FootBall</span></a></li> <a id='1link_1b' title="soccer" onclick='showSports(this); changeTab(this);'><span>Soccer</span></a></li> <a id='1link_1c' title="baseball" onclick='showSports(this);'><span>Baseball</span></a></li> Hi, Does anyone know if there is a event or something that fires when Javascript finishes executing. When I load a page, the body's onLoad event fires when it has finished loading but there might be some Javascript that is still running (or javascript that is triggered from the onLoad event itself). And this javascript could add to the page's DOM. So is there any way to detect when the page has REALLY finished loading (ignoring the possibility of setTimeout() etc). I need to know this as I am constructing a webpage-scraper and therefore I need to know when the pages have completely loaded. Thanks, I searched the forum for an answer to this question, but found nothing that was able to answer my question. I have a form and I need to validate a field against three rules: 1) The field need to be between 6 and 12 characters 2) It can only have letters, numbers, and the underscore 3) It cannot contain a space or other special characters I want the validate to happen in real-time. I have the first rule working great. Here is the code for that: Code: var username = document.getElementById('registerUsername'); if((username.value.length < 6) || (username.value.length > 12)) { document.getElementById('usernameValidate').innerHTML="Incorrect."; }else{ document.getElementById('usernameValidate').innerHTML="Correct."; } How would I be able to incorporate checking for rules 2 and 3? How do I join strings? I tried below but get an error. var a += document.getElementById("PICKUP_TYPE").value + "~"; var a += document.getElementById("PICKUP_ADDRESS").value + "~"; var a += document.getElementById("PICKUP_ADDRESS2").value + "~"; I'm new at JavaScript and am trying to figure out a simple text calculator as seen on a science project website. The project says the final program should calculate: 1. the number of sentences contained in the text, 2. the number of words in each sentence, 3. the number of letters in each word, 4. the average number of words per sentence, and 5. the average word length. I have pretty much everything (I think) but am being completely stumped by item number 2 and item number 4. The code is below. Can anyone help me understand what I should be doing for point number 2 and 4? I understand how to calculate and display the length of an item in an array and return it's values as 5,6,7,8 etc where the value is the length of the word, but i can't grasp how to calculate the number of items in an array to read 2,5,9 where the values are the number of words per each sentence...so confused! Below is my code...apoligies if it's sloppy...it's my first javascript code experience Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Count</title> Code: Okay so I have this code for HMTL5 Canvas, however this is a JavaScript directed question not a Canvas question. Code: <script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); cxt.moveTo(0,400); cxt.lineTo(50,a); cxt.lineTo(100,b); cxt.lineTo(150,390); cxt.lineTo(200,300); cxt.lineTo(250,285); cxt.lineTo(300,299); cxt.lineTo(350,250); cxt.lineTo(400,325); cxt.lineTo(450,275); cxt.lineTo(500,300;); cxt.stroke(); </script> That will draw a line graph, however I want to get the coordinates from a variable in the URL. So it may be example.com/a=500&b=600 . How would I retrieve these two variables and then insert in to they're respective places? Any help greatly appreciated, please make it as simple as possible - I'm good with my PHP now but JavaScript is all new |