Question
Answer and Explanation
In JavaScript, the replace()
function can be used with the dollar sign ($) to perform powerful string manipulations, particularly when working with regular expressions. The dollar sign acts as a special character that allows you to reference captured groups from the matched pattern.
Here's a breakdown of how to use the dollar sign with replace()
:
1. Basic Usage with Captured Groups:
- When you use parentheses in a regular expression, you create a "captured group." These groups can be referenced in the replacement string using $1
, $2
, $3
, and so on, where $1
refers to the first captured group, $2
to the second, and so forth.
2. Example:
let str = "John Doe";
let newStr = str.replace(/(\w+) (\w+)/, "$2, $1");
console.log(newStr); // Output: "Doe, John"
- In this example, (\w+)
matches one or more word characters. The first (\w+)
captures "John", and the second captures "Doe". The replacement string "$2, $1"
swaps the order of these captured groups, resulting in "Doe, John".
3. Other Dollar Sign Patterns:
- $$
: Inserts a literal dollar sign ($) into the replacement string.
- $&
: Inserts the entire matched substring.
- $`
: Inserts the portion of the string that precedes the matched substring.
- $'
: Inserts the portion of the string that follows the matched substring.
4. Example with Other Patterns:
let str = "Hello World!";
let newStr1 = str.replace("World", "$$");
console.log(newStr1); // Output: "Hello $!"
let newStr2 = str.replace("World", "$&");
console.log(newStr2); // Output: "Hello World!"
let newStr3 = str.replace("World", "$`");
console.log(newStr3); // Output: "Hello Hello "
let newStr4 = str.replace("World", "$'");
console.log(newStr4); // Output: "Hello !!"
5. Important Considerations:
- The dollar sign patterns are only interpreted when the first argument of replace()
is a regular expression. If the first argument is a string, the dollar sign will be treated as a literal character.
- Be mindful of the order of captured groups when using $1
, $2
, etc. Incorrect ordering can lead to unexpected results.
By understanding these patterns, you can effectively use the dollar sign with JavaScript's replace()
function to perform complex string manipulations and transformations.