1

I have a lot of sections like the example below:

<section class="section1">
    <div>
        blabla content1 blabla
    </div>
</section>
<section class="section2">
    <div>
        blabla content2 blabla
    </div>
</section>


I use regex to match e.g. 'content1'. But now I want to get the sections' class in which 'content1' is located. Unfortunately I am very new to regex can't figure out how to do this. I even get in trouble when I try to match only the string 'section':

sectionClass = new RegExp ('section(?=content1)','i');

This doesn't work.

Can you give me a hint or tip how to write the regular expression?

EDIT: I stored the code in a variable using .html()

luca
  • 137
  • 1
  • 8
  • 7
    Rule 1, don't parse HTML with RegEx. Rule 2, if you want to use RegEx to parse HTML see rule 1 – freefaller Sep 09 '13 at 12:28
  • 3
    Try `$('section:contains("content1")').attr('class')` – Arun P Johny Sep 09 '13 at 12:28
  • http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – faino Sep 09 '13 at 12:35
  • @freefaller so I should not using RegEx to parse HTML but it works anyways? – luca Sep 09 '13 at 12:49
  • @ArunPJohny This works so far but can i use a variable instead of "content1"? Such like `$('section:contains('+variable+')').attr('class')`? The result of this is 'undefined' – luca Sep 09 '13 at 12:51
  • what is the value of the `variable` – Arun P Johny Sep 09 '13 at 12:53
  • @luca, the rules surrounding HTML are not strict enough for the use of RegEx, and therefore is prone to error when attempting to match against it. It might work here, but it's use is highly discouraged, as the number of "up votes" my comment has received hopefully demonstrates – freefaller Sep 09 '13 at 12:55
  • @ArunPJohny in this case it's either 'content1' or 'content2', depending on what i want to look for. – luca Sep 09 '13 at 13:01
  • it seems fine `var variable = 'content1'; var clazz = $('section:contains("' + variable + '")').attr('class'); ` http://jsfiddle.net/arunpjohny/rtTXp/1/ – Arun P Johny Sep 09 '13 at 13:04
  • @freefaller I believe you when you say so, I was just wondering that it works in my cases so far. And since I have no idea how to get what I want without parsing HTML with RegEx I have to do so. – luca Sep 09 '13 at 13:04
  • @ArunPJohny this works fine, thanks. Do you want to put it in an answer, then I can accept it as best answer. – luca Sep 09 '13 at 13:26

2 Answers2

0

Here is the code:

var re=/<section\s+class=\"(\w+)\".+content1/;
var result = re.exec(s)[1];
fred02138
  • 3,323
  • 1
  • 14
  • 17
0

Try

var variable = 'content1';
var clazz = $('section:contains("' + variable + '")').attr('class');
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531