Closed Bug 22950 Opened 25 years ago Closed 25 years ago

RegExp usage in replace function messes up replace result

Categories

(Core :: JavaScript Engine, defect, P3)

x86
Windows NT
defect

Tracking

()

RESOLVED FIXED

People

(Reporter: rogerl, Assigned: rogerl)

Details

From :        Josh Gough <exv@randomc.com>

Hi,
          I was trying to use a function as the 2nd parameter
  to a String.replace call, and then I used another separate regular
  expression
  inside that function, and it ends up clobbering the rightContext of the
  first expression. Is this how it is supposed to work? I'm not sure if I
  actually
  need to use a second regex in the simple example below, but certainly
  there
  are cases when it would be needed.

  When I try to run this through xpcshell of m12:

  var str = "%C8,2blah blah%Bbold %Uunderline%C8,7more color";
  var format_regex = /(%C|%B|%U)(\d{0,2})(,{0,1})(\d{0,2})/ig;
  var colors_regex = /,/;

  function replaceFunc(s, format_flag, num1, comma, num2) {
          print ("");
          print ("num1: " + num1);
          print ("comma: " + comma);
          print ("num2: " + num2);
          print ("The right context: " + RegExp.rightContext);
          print ("The lastIndex??: " + format_regex.lastIndex);

          var colors_str = s.substring(2);
          s = s.substring(0,2);
          var colors_ary = colors_str.split(colors_regex);
          print (colors_ary);n
          print ("The right context: " + RegExp.rightContext);

          return "*";
  }

  print ("\n" + str.replace(format_regex, replaceFunc));

  I get this:

  num1: 8
  comma: ,
  num2: 2
  The right context: blah blah%Bbold %Uunderline%C8,7more color
  The lastIndex??: 0
  The colors array: 8,2
  The right context: 2

  num1:
  comma:
  num2:
  The right context: bold %Uunderline%C8,7more color
  The lastIndex??: 0
  The colors array:
  The right context: bold %Uunderline%C8,7more color

  num1:
  comma:
  num2:
  The right context: underline%C8,7more color
  The lastIndex??: 0
  The colors array:
  The right context: underline%C8,7more color

  num1: 8
  comma: ,
  num2: 7
  The right context: more color
  The lastIndex??: 0
  The colors array: 8,7
  The right context: 7

  *blah blah*bold *underline*7

  For some reason the second call messes up the next match, hence
  it returns "*7" instead of *more color. Anyone have any ideas?

  Thanks,
  Josh
Status: NEW → ASSIGNED
The rightContext is added onto the replacement string AFTER the lambda executes,
it needs to be preserved around that call.
Fix checked in.
Status: ASSIGNED → RESOLVED
Closed: 25 years ago
Resolution: --- → FIXED
You need to log in before you can comment on or make changes to this bug.