December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 38 | Creating Lazy Quantifiers with the Question Mark |
Suppose your task is to write a script that reduces the size of HTML files by removing all comments. The syntax for an HTML comment is <!-- Comment -->. So, to accomplish this task, you might assume that you just need to remove the opening and closing brackets of the comment syntax and any characters that exist between them:
| | const re = /<!--.*-->/; |
| | const str = "HTML comment: <!-- I'm a comment -->"; |
| | |
| | str.replace(re, ""); // → "HTML comment: " |
Here, the full stop (.) matches any character (except for a line break), and the quantifier * tells the engine to do this zero or more times. This pattern works for a single-line comment. What ...
Read now
Unlock full access