Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Javascript regex backrefering

Name: Anonymous 2012-02-22 12:29

In Perl, this will successfully backreference TeXt.


  my $str = "this is TeXt";;

  if ( str =~ /(TeXt)/g ) ) {
    $str = $1;
  }


However, if I try something similar in Javascript:



  var str = "this is TeXt";;

  if ( str.match(/(TeXt)/g) ) {
    str = $1;
  }


This will not backreference TeXt

Any idea how I can access the captured group within the If block in Javascript?

Name: Anonymous 2012-02-22 17:17

>>3
The way Perl puts stuff in $1 and such is by having global variables(!) that get assigned to by the regexp parser. Javascript doesn't do this thank god. Your code should instead look something like this:

var matches = str.match(/(TeXt/g);
if (matches) {
    // do something with matches
}


You should look up the documentation for this on Mozilla's developer site (https://developer.mozilla.org/en/JavaScript).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List