December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 42 | Forcing . to Match Newline Characters with the s Flag |
Suppose you want to write a script that removes all comments from JavaScript files to reduce their file size. Removing single-line comments is easy: just find a line that starts with double forward slashes and delete the entire line.
But removing block comments with the /* */ syntax that may span multiple lines is a bit trickier. You might expect a pattern like /\/\*.*\*\// to work because it finds a /* followed by any character until it reaches */.
But, the full stop token in this pattern won’t match line break characters, so the regex could fail:
| | const re = /\/\*.*?\*\//; |
| | |
| | const comment = `/* this |
| | is a multiline |
| | comment ... |
Read now
Unlock full access