0

I am most interested in learning more about that piece at the end, '\\$&'

I'm not really sure what its doing, or how it works, but it gets the job done.

The code that I have:

function escapeRegExp(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
  }

  const searchRegex = new RegExp(
    searchQuery
      .split(/\s+/g)
      .map(s => s.trim())
      .filter(s => !!s)
      .map(word => `(?=.*\\b${escapeRegExp(word)})`).join('') + '.+',
    'i'
  )

1 Answers1

0

$& is defined in MDN's String#replace -- Specifying a string as a parameter reference as

Pattern $& Inserts the matched substring.

Essentially, this gives you back the entire matched substring. In your example, \\ prepends a single backslash, effectively escaping the match.

Here are some examples:

// replace every character with itself doubled
console.log("abc".replace(/./g, "$&$&"));

// replace entire string with itself doubled
console.log("abc".replace(/.*/g, "$&$&"));

// prepend a backslash to every match
console.log("abc".replace(/./g, "\\$&"));

// behavior with capture groups that can be accessed with $1, $2...
console.log("abc".replace(/(.)(.)/g, "[ $$1: $1 ; $$2: $2 ; $$&: $& ]"));
ggorlen
  • 26,337
  • 5
  • 34
  • 50