0

I have multiple different text strings I need to replace on the client side.

Let's say I want to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog".

I've been trying to extend this question to handle multiple replacements.

$("#container h3 a").text(function () {
  return $(this).text().replace("Red Apple", "Orange Orange"); 
  return $(this).text().replace("Sad Cat", "Happy Dog");
});

I'm finding that only the first replacement is returned.

I'm having trouble figuring out how to return multiples, not getting the desired result like this either.

return {
  ...
}

Rationale for this not being a duplicate: Note that I am not trying to replace just Apples but also Cats.

Community
  • 1
  • 1
AllInOne
  • 1,450
  • 2
  • 14
  • 32

3 Answers3

4

Your first return ends the function. The second return is never reached.

But you can chain the replacements.

$("#container h3 a").text(function () {
    return $(this).text().replace("Red Apple", "Orange Orange").replace("Sad Cat", "Happy Dog");
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 3
    Yes. Worth adding that the reason @AllInOne's code is breaking is because a function effectively ends once it `return`s. – Jon Uleis Dec 21 '16 at 16:31
1

Once your code reaches a return statement, no code after that will be processed. return literally returns control to the caller code.

As MDN states:

The return statement ends function execution and specifies a value to be returned to the function caller.

You can deal with issues like this in a couple of ways:

  1. You could build up a value and then return that value:

    $("#container h3 a").text(function () {
    
      // Work on your return value as much as you want
      var retVal = $(this).text();
      retVal = retVal.replace("Red Apple", "Orange Orange");
      retVal = retVal.replace("Sad Cat", "Happy Dog");
    
      return retVal;  // And then return it (just once)
    });
    

    Note that there is absolutely nothing wrong with this approach as it is easy to read and understand.

  2. Or, in this case, you can just chain the .replace() calls because each time you call .replace() it returns a new string that you can then call .replace() on. The final string will be returned as the value that the original return actually sends back:

    $("#container h3 a").text(function () {
      return $(this).text().replace("Red Apple", "Orange Orange")
               .replace("Sad Cat", "Happy Dog");
    });
    

    Note that this approach accomplishes the exact same thing, but it is more compact, precise and eliminates the need for a temporary storage variable.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

I think you should be able to do it by calling replace twice in one return statement.

return $(this).text().replace("Red Apple", "Orange Orange").replace("Sad Cat", "Happy Dog");