1

I'm wondering how to change this exact php regex feature into javascript?

$ismatch= preg_match('|She is a <span><b>(.*)</b></span>|si', $sentence, $matchresult);

if($ismatch)
{
      $gender= $matchresult[1];
}
else{ //do other thing }
i need help
  • 2,386
  • 10
  • 54
  • 72
  • Bad news, JS doesn't support the dotall switch http://stackoverflow.com/questions/1068280/javascript-regex-multiline-flag-doesnt-work – Petah Mar 04 '12 at 11:33
  • This could be a good question if phrased properly and the focus was on the dotall modifier... in its current state it sounds like a "Do the work for me" question. – Felix Kling Mar 04 '12 at 11:36

1 Answers1

3

This is not quite trivial since JavaScript doesn't support the s modifier.

The equivalent regex object would be

/She is a <span><b>([\s\S]*)<\/b><\/span>/i

The functionality of the code (extracting group 1 from the match if there is a match) would be done in JavaScript like this:

var myregexp = /She is a <span><b>([\s\S]*)<\/b><\/span>/i;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
} else {
    // do other thing
}
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 1
    Information about the `[\s\S]` approach can be found at [MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp): *(The decimal point) matches any single character except the newline characters: `\n` `\r` `\u2028` or `\u2029`. (`[\s\S]` can be used to match any character including newlines.)* – Felix Kling Mar 04 '12 at 11:34
  • Or use the special JS feature `[^]`, it matches any character. – Qtax Mar 04 '12 at 11:50
  • @Qtax: Wow, I'd never seen this before. Is there any documentation about this? – Tim Pietzcker Mar 04 '12 at 12:15
  • @Tim, don't know, haven't seen it documented, but haven't really looked for it either. Unlike Perl/PCRE in JS the first unescaped `]` seems to end the character class without exceptions, thus `[^]` would match everything except nothing, i.e everything. – Qtax Mar 04 '12 at 13:08