December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 35 | Taking Away the Special Meaning of Replacement Patterns |
Suppose your task is to add the pricing for different services to a website’s blog. More specifically, you need to add the fee for tire replacement at a car service center. In your first attempt, you come up with a solution like this:
| | const str = "In our shops, tire change takes about 15 minutes."; |
| | const re = /\b(tire change)\b/; |
| | |
| | str.replace(re, "$1 (which cost $10 for each tire)"); |
| | // → "In our shops, tire change (which cost tire change0 for each tire) |
| | // takes about 15 minutes." |
This regex attempts to find the phrase “tire change” in a string and add the cost in parentheses. It uses a special replacement ...
Read now
Unlock full access