sw0o0sh Posted January 22, 2011 Share Posted January 22, 2011 I've used preg_match() in PHP but I can't seem to figure out how to accomplish what I need to do with JavaScript. I've checked out a lot of RegExp tutorials but don't understand still how to capture something between quotes and then make it act as a variable. For instance, <img src="image.gif" class="image_01" alt="sample image" /> I'm trying this but it's not working <script type="text/javascript"> function runCheck() { var data = document.getElementById("test").innerHTML; var pattern = /class\=\'(.*)\'/; var checkSprite = data.match(pattern); alert(checkSprite); } </script> I'm trying to grab what is inside of "class=''" Quote Link to comment https://forums.phpfreaks.com/topic/225280-matching-with-regexp/ Share on other sites More sharing options...
sw0o0sh Posted January 22, 2011 Author Share Posted January 22, 2011 nevermind, seems to have worked with: var pattern = /class\=\"(.*)\"/i; However it returns two matches, the second one being most appropriate(it returned class="sprite", and sprite). Perhaps knowing how to make it more specific would be useful but I'd say it's solved. Quote Link to comment https://forums.phpfreaks.com/topic/225280-matching-with-regexp/#findComment-1163422 Share on other sites More sharing options...
haku Posted January 22, 2011 Share Posted January 22, 2011 Edit: I just read your reply typed while writing my own, and it seems like you've almost got it worked out, but you may find my solution usable anyways: I'm no pro in regex and particularly in javascript regex, but I know the javascript regex engine is not as advanced as in other languages. As such I don't think that you can capture something in the middle surrounded by parenthesis like that in javascript (I could be wrong though). Maybe go with something a little simpler: var string = '<a href="#" class="my_class">'; var start = string.indexOf('class="') + 7; var end = string.indexOf('"', start + 1); var result = string.substring(start, end); (note: not checked - you may need to play with the numbers a bit) Quote Link to comment https://forums.phpfreaks.com/topic/225280-matching-with-regexp/#findComment-1163423 Share on other sites More sharing options...
.josh Posted January 22, 2011 Share Posted January 22, 2011 When there is a match, the first element in the matched array (element 0) is always the full pattern match. Everything between your /.../ forward slashes is the full pattern. Each element after that represents the matches for each captured group you have in the pattern. Captured groups are the parts of the pattern between the parenthesis. Quote Link to comment https://forums.phpfreaks.com/topic/225280-matching-with-regexp/#findComment-1163438 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.