2022-07-14

JS: Regex replacement with matching groups

When doing a .replace() with regex, you might want to replace some group of strings, but leave some of it. Of course, you can use group matching. To do that, simply use $n where n is a positive number from 1-100 representing the matched group number. Example:

fileName = 2022-07-15-some-title.md;
fileName.replace(/(\d{4}-\d{2}-\d{2}-)(.*)(\.md$)/, '$2');

// the result of the replace will be...
// "some-title"

If we have a fileName = 2022-07-15-some-title.md then the code above will only replace with the second ($2) matching group. The result will be some-title