Using Lodash _.replace to Swap String Values

This article provides an overview of using the _.replace method in the Lodash JavaScript library to swap values within a string iteratively. It covers the limitations of basic sequential replacement, demonstrates how combining _.replace with regular expressions and custom replacer functions achieves safe, single-pass value swapping, and details the execution process with practical code examples.

In JavaScript, swapping two or more values in a string (such as changing all instances of "foo" to "bar" and all instances of "bar" to "foo") presents a common pitfall: sequential replacement. If you replace "foo" with "bar" first, a subsequent replacement of "bar" with "foo" will erroneously overwrite the values you just converted. To avoid this collision, replacements must occur in a single, iterative traversal over the target string.

Lodash provides the _.replace utility method to handle string replacements cleanly. Its syntax mirrors the native String.prototype.replace() method:

_.replace([string=''], pattern, replacement)

While replacement can be a static string, it can also be an invokee function (replacer callback). When paired with a global regular expression (RegExp), _.replace iterates through every match in the source string, passes the matched token into the callback function, and substitutes it with the function’s return value.

Implementing an Iterative Value Swap

To swap values simultaneously, construct a regular expression that matches all target tokens using the alternation operator (|) and the global flag (g). Then, pass an object map to the replacement function to iteratively swap the matched values.

const _ = require('lodash');

const input = 'cats and dogs sleeping with dogs and cats';

// Define the swap dictionary
const swapMap = {
  cats: 'dogs',
  dogs: 'cats'
};

// Create a regex matching any of the keys globally
const pattern = /cats|dogs/g;

// Perform the iterative swap
const result = _.replace(input, pattern, (match) => swapMap[match]);

console.log(result);
// Output: "dogs and cats sleeping with cats and dogs"

How the Iteration Works

  1. Pattern Evaluation: The regular expression scans the string from left to right. When it identifies either "cats" or "dogs", it stops at that specific match.
  2. Callback Invocation: Lodash invokes the callback function, supplying the matched token as an argument.
  3. Lookup and Substitution: The function queries swapMap with the matched token and returns its counterpart ("cats" becomes "dogs", "dogs" becomes "cats").
  4. Pointer Advance: The regex engine advances past the matched substring, ensuring that the newly inserted replacement is not rescanned or re-evaluated during the current pass.
  5. Completion: Lodash constructs and returns the finalized string once all matching indices have been traversed.

This iterative approach ensures that string swaps occur atomically in linear time without creating race conditions or requiring temporary placeholder tokens.