Recipe 40 | Generating Indices for Matches with the d Flag |
Task
Suppose you’re building a tool that helps detect errors and potential problems in JavaScript code. You need your tool to be able to detect the use of reserved words in variables and functions and warn the user.
Ideally, you want to program your tool to pinpoint the exact part of the code where the reserved word is misused rather than outputting just a line number. So, if the code has a variable assignment with a reserved word like this:
| let default = 7; |
You want to indicate the error like this:
| let default = 7; |
| ↑------ Invalid variable name |
To achieve this task, you need a regex that provides the start and end indices of the match.
Solution
Send the supplied code one line ...
Get Text Processing with JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.