JavaScript - Regex Problem
Similar TutorialsI am using the below regex to extract the subdomain from the url Code: ^(?!www)([^.]+)\.mydomain\.com The above code extracts subdomain only when the url is typed as Quote: subdomain.mydomain.com But I need a regex which extracts sudomain when the url is typed with WWW and without WWW as below Quote: subdomain.mydomain.com www.subdomain.mydomain.com Kindly help me. Hi all, I have a string which contains HTML and *possibly* IMG tags. I am trying to extract part of each IMG tag which may be in the string. The string is part of a chat-box message which may or may not contain smilies. Here is a typical line of text, without processing (note I mis-spell the bbcode "quote" so as not to fool this board): Code: [qoute="Krupski"]<img src="./images/smilies/smile.gif" alt=":smile:" title="smile" /> <img src="./images/smilies/thumbsup.gif" alt=":thumbsup:" title="thumbsup" /> <img src="./images/smilies/thumbsdown.gif" alt=":thumbsdown:" title="thumbsdown" />[/qoute] Notice that each image has an "ALT" attribute which contains the smiley code of the smiley image. THAT is what I want to extract. This is the regex I am using to grab each smiley code: Code: txt = txt.replace(/<img(?:.*?):(.*?):(?:.*?)\/>/gi,':$1:'); The weird thing is, the regex grabs the FIRST and LAST of the three, but not the middle one! I'm sure the stupid mistake is sitting right in front of my face, but I'm not seeing it. Any help will be greatly appreciated! Thanks. -- Roger Hi all, First... this isn't homework... Now, I'm trying to make a live Regular Expression evaluator and I thought it would be really simple, but it's not working. Here's the JS I wrote..... Code: <html> <head> <style type="text/css"> body { background-color:#ddeeff; } textarea#inp1, textarea#inp2, textarea#out1 { margin:0 25%; margin-bottom:1%; border:0; padding:0; width:50%; height:100px; border: 1px solid #000000; } p { margin:0 25%; } </style> <script type="text/javascript"> function test() { var inp1 = document.getElementById('inp1'); /* regex in here */ var inp2 = document.getElementById('inp2'); /* test string here */ var out1 = document.getElementById('out1'); /* results here */ r = inp1.value.split(','); /* get find , replace */ var str = inp2.value; var find = r[0] || ''; var repl = r[1] || ''; var result = str.replace(find, repl); out1.value = result; } </script> </head> <body> <p>regex</p> <textarea id="inp1"></textarea> <p>test string</p> <textarea id="inp2"></textarea> <p>result</p> <textarea id="out1"></textarea> <script type="text/javascript"> setInterval('test()', 100); </script> </body> </html> Now, it DOES work if I do something simple like enter the word "Test" for the test string and T,X for the "regex" (the result transforms into "Xest" as it should). But if I put in something like this: /<p(.*?)>(.*?)<\/p>/gi,'$2' for the regex and <p class="test">Hello</p> for the test string The result is <p class="test">Hello</p> when it should be just Hello I can put regex strings into an array and of course it works (for example): Code: var find = [/<p>/g,/<\/p>/g]; var repl = ['P open', 'P close']; var n = find.length; while (n--) str = str.replace(find[n], repl[n]); ...blah...blah... So why doesn't my code work when I'm using variables that contain find and replace strings??? Am I missing something, or can it not be done this way? -- Roger (edit to add): The above code is online HERE Code: var bakaBanner; bakaBanner = document.getElementById('head'); if (bakaBanner) { var str=/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/; document.write(str.replace(/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/, "http://img218.imageshack.us/img218/5904/revyblacklagoon1.png")); } Alright, here's the deal... This is a script to be used in Greasemonkey. The page this is for changes their banner every 5 minutes, the name changes and it could be either jpg or png. I'm fairly certain my regex itself: \/images\/banners\/[A-Za-z0-9_]+.[a-z]+ Is correct... Here's an example of what it's looking through: Code: <div id="head" style="background-image: url(/images/banners/kiminitodoke.jpg);" > <div id="header_left"> <div id="rss"> My guess is that it has something to do with this line: document.write(str.replace(/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/, "http://img218.imageshack.us/img218/5904/revyblacklagoon1.png")); I'm new with Javascript, so I don't really understand why it's not working... :/ Hi, I'm using this site Translator Editor - LingoJam I'm trying to use the regex portion of the site (click regex on the page that link goes to) to create a substitution cipher - a translates to o, etc. so far I have Code: /a/g -> o /o/g -> u Theoretically, that'd mean when I typed in "a", it would translate to "o", and when I typed in "o", it would translate to "u". Trouble is, it doesn't know when to stop. I type in "a" and it immediately returns "u", because it substitutes the "o" that it should end up as for the "u". Any help on this matter would be appreciated. Thank you. Reply With Quote 12-29-2014, 08:34 AM #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 That is bound to occur if you use onkeyup to translate the letter immediately it is typed. You should create the cyphered text once the whole message is complete. All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit. Should alert '' twice , instead alerts original text Code: text = 'p18=100'; text = text.replace("(^|&)p100=18.*?(&|$)","") alert(text); text = text.replace(/(^|&)p100=18.*?(&|$)/g,"") alert(text); tested regex on online tester and it should be OK. ? I am creating a userscript and trying to take the following: Arian Foster (Hou - RB) and end up just with the team name: Hou You can't remove by index (which I would be able to do), because it might be K instead of RB or NO instead of Hou. I am assuming that you use Regex and the replace function to do so, but I am struggling with understanding all Regex symbols. Can someone help me with this and explain it briefly? I would appreciate it. I have this code so far; PHP Code: validatePhone : function(field, caption) { phoneNumber = /^[0-9]{11}$/; if(phoneNumber.test(field.val())) { return true; } return i18n('phone', caption); }, It works fine for entering an 11 digit number. However, I want to check that the number starts with either 077, 075, 079 or 078. Also, if the field is empty then it can also be accepted. How would I do this? Thanks THIS IS NOT HOMEWORK Hi all, I'm trying to extract a URL from a string that may or may not have extra characters before and/or after the URL. I'm having a heck of a time making the regex work... when it works for one case it fails for another and I'm just not seeing why. OK, here is the code: Code: var str = 'leading junk http://h71036.www7.hp.com/hho/images/Outdoor_scene.jpg trailing junk'; var txt = str.replace(/^\s?((https?|ssh|ftp|mailto|file|www):\/\/.*?)\s?$/gi,'href:\n1 is $1\n2 is $2\n3 is $3'); alert(txt); (eventually the replacement string will be <a href="$1">$1</a> of course) What I want is of course to extract "http://h71036.www7.hp.com/hho/images/Outdoor_scene.jpg" out of the string whether of not there is leading and/or trailing "junk" around the string. Any ideas? I'm stumped... Thanks! -- Roger I am trying to grab all text between <START> and <END> and have the following bits of code, but neither are returning anything. I use JS so rarely that I can't see where the problems are - Code: var ermtext = response.match(/<START>(.*?)<END>/i); if (ermtext) { result.ermtext = ermtext.replace("$1"); } Code: var patt=/<START>(.*?)<END>/i; result.ermtext = response.match(patt, "$1"); Hi: I think this is where I need to ask this. I am doing a PHP/mod_rewrite and I need to tweak one of the RegEx's used in it but I don't know the syntax. I have this bit of code: Code: <a href="http://www.mywebsite.com/Promotional.Products-Promotional.Items/Promotional-Products/<?php echo $product_id ?>-<?php echo str_replace(" ", "-", $myTitle) ?>-<?php echo $full_state ?>-Promotional-Products.html" title="<?php echo $myTitle?> <?php echo "$full_state"; ?>"><?php echo $myTitle?></a> RewriteRule ^Promotional.Products-Promotional.Items/Promotional-Products/([0-9]+)-([a-zA-Z]+)-([a-zA-Z]+)-Promotional-Products.html$ Promotional.Products-Promotional.Items/Promotional-Products.php?product_id=$1&myTitle=$2&full_state=$3 I wanted to know how I can revise the middle RegEx: Code: ...-([a-zA-Z]+)-... to include replacing all spaces with hyphens. Can someone help me with this, please. Thanks! Hi - I am trying to use this code to validate, function test() { var pattern = (/^\d{3}[-]?\d{2}[-]?\d{4}$/g); var pattern1 = (/^d{3}$/g); if(!pattern.test(document.myform.textInput.value)||(!pattern1.test(document.myForm.textInput.value)) ) { alert("Error!"); } } using regular expressions to compare a string from an input with two patterns that could both be valid. Therefore I'm pretty sure I need to use "||" between them both. I can't quite figure out how to get javascript to check for both patterns, only the first seems to be checked as valid. Is it something to do with the way I have my brackets? Can someone point me in right direction, Thanks i'm trying to make a validation page and i am having issues with some of them AGE - i'm not sure where to go from here Code: var age = /^[0-9 ]{3,20}$/; // trying to check age (only 18-25 is valid) Name - how do i make it so that no spaces are allowed? Code: /^[A-Za-z ]{3,50}$/ street - i have no clue where to even begin on this. i think that RegEx can't be used to validate all addresses, but something simple like 123 main street. maybe something like this Code: preg_match('/.{2,60}$/',$address) here's an example of my zip code one to give you an idea of what im going for Code: function checkZip(){ var re5digit=/^\d{5}$/ //regular expression defining a 5 digit number if (document.myform.zip.value.search(re5digit)==-1) //if match failed alert("Please enter a valid 5 digit number inside form") } HTML FORM Code: <form name="myform" onsubmit="return checkZip()"> <fieldset> <legend>Test Form</legend> Firstname*: <input type="text" name="firstname"/><br/> Lastname*: <input type="text" name="lastname"/><br/> Street*: <input type="text" name="street"/><br/> City*: <input type="text" name="city"/><br/> State*: <input type="text" name="state"/><br/> Zip*: <input type="text" name="zip"/><br/> Age*: <input type="text" name="age"/><br/> Gender*: <input type="text" name="gender"/><br/> Major/Program Choice*: <input type="text" name="major"/><br/><br/> <input type="reset" /> <input type="submit" /> what is a good way to combine these into all one function using getElementByID? i could make another function and put all the other functions in it, but i'm not sure where i can incorporate getElementByID when the verification is complete, i want to display all the info using getElementByID and innerHTML. should i make vars that hold all the info and put in after a span somewhere? Hi All, i have this Regex which is below and im trying to validate a field when a button is clicked i may have this mest up but what the regex does it checks for 1 decimal place and returns true or false i put some comments in with the code Code: function IsNewBid() { var NewBid = document.getElementById('MainContent_txtNewBid').value; var result; result = ^[0-9]{1,10}[.]{1}[0-9]{1,2}$|^[0-9]{1,10}$(NewBid .Value) if (result 'Equals False So theres and error') Do something else{ carry on } } Any help will be highly appreciated.. Thank you for your time. I am attempting to remove all HTML tags with nothing in the middle. For example, I want to remove this Code: <b><i><u> </u></i></b> I've written an expression that does that, but there's an issue with it. Here's my regex: Code: messageVal = messageVal.replace(/(<[^\/>]*>)+[\s]*(<\/[^>]*>)+/g,''); The issue is that I only want to delete as many end tags as I found open tags. An example that my regex doesn't work on is... Code: <b> hello <u><i> </i></u></b> The current regex will output: Code: <b> hello I need it to return: Code: <b> hello </b> Any ideas? I am trying to run a simple replace over some css a user puts into a textarea. I would like to remove all the comments Code: /* MY COMMENT */ I have tried the following to try and escape the forward slashes but to no avail. Code: replace(/\/*(.*)\//g,""); any ideas? Thanks! Hello, I have this piece of code I read from a book to remove text nodes that only have white space. Code: if (node.nodeType == 3 && ! /\S/.test(node.nodeValue)){ // code to remove the text node } Why should we use this: Code: ! /\S/.test(node.nodeValue) Instead of this? Code: /\s/.test(node.nodeValue) The following code works as required - Code: if (result.marc.f695.subfields['a'] != "Electronic journals" && result.marc.f695.subfields['a'] != "electronic journals") { return; } However, this isn't the most efficient way to code it, especially as I want to add further possibilities, most beginning with "[Ee]lectronic. I know I need to use regexes, and think the code I need to use is something like /[Ee]lectronic/, but I use JavaScript so rarely that I'm not sure how to build this into the above expression. Can anybody help? Hey everyone, I'm working on a script, but I've been stopped by an error code from regex's match function. Firefox is giving me a "text.match is not a function". My assumption is that it may be the getSelection that is causing the error. Any clarification would be much appreciated! Code: function captureText(){ var txt = ""; if(window.getSelection){ var text = window.getSelection(); } else if(document.selection){ var text = document.selection.createRange().text; } else { return; } if(text != ""){ var reg = /^[A-Z](.*?)+(\.)$/g; var check = text.match(reg); alert(check); alert("You selected: "+text); if(window.getSelection){ window.getSelection().removeAllRanges(); } else if(document.selection){ text.blur(); document.selection.empty(); } else { return; } } } document.onmouseup = captureText; Thanks. hi, Getting on quite well, I feel. just would like you to confirm that this regex will strip out characters that cannot be in a phone number those are (imv) 0-9 - ( ) + Code: val = val.replace (/[^0-9\\s\\-\\(\\)\\+]/gi,""); // strip the characters that cannot appear in a phone number I use double backslashes to keep the perl interpreter happy. otherwise (in case it simplifies it for you), it would be Code: val = val.replace (/[^0-9\s\-\(\)\+]/gi,""); // strip the characters that cannot appear in a phone number bazz |