user4277027
user4277027

Reputation:

JavaScript recursion returns intermediate results rather than the final result

I have this JavaScript code where the rec() function is called by itself. The intent with this code is to loop through HTML-like text and replace all occurrences of the regex "IMG(.*)tid".

Once it has processed the string it should output the final version of the string in the "newText" variable (on line 5).

var text = '<IMG tid="302293901" title="test"><P></P><IMG tid="302293901" title="test">';
alert("source text: " + text);

var newText = rec(text);
alert("final source text: " + newText);

function rec(str) {
  var i = str.search("IMG(.*)tid");
  alert("value of i: " + i);
  if (i > -1) {
    str = str.replace("IMG", "BLA");
    alert("modified source text: " + str);
    rec(str);
  }
  return str;
}

When this code runs it does modify the source string in the "text" variable, replacing all occurrences of "IMG" with "BLA". During it's execution the function displays the expected final string that looks as shown below.

expected final results

However the problem with this is that the alert box on line 5 does not return the results shown above, but an intermediary result (where only one of the "IMG" entries has been replaced).

The returned string is shown below.

actual final results

So this code is probably incorrectly structured but in what way?

Upvotes: 0

Views: 75

Answers (2)

IMTheNachoMan
IMTheNachoMan

Reputation: 5811

You need to return the value of rec...

function rec(str) {
  var i = str.search("IMG(.*)tid");
  alert("value of i: " + i);
  if (i > -1) {
    str = str.replace("IMG", "BLA");
    alert("modified source text: " + str);
    return rec(str);
  }
  return str;
}

Upvotes: 0

Dave Kennard
Dave Kennard

Reputation: 467

When you run rec again from within rec, you're not doing anything with the returned result. You need to change it to str = rec(str)

Upvotes: 3

Related Questions