Jump to content

Recommended Posts

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=''"

Link to comment
https://forums.phpfreaks.com/topic/225280-matching-with-regexp/
Share on other sites

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.

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)

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. 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.