That is the markup parser’s task.
In case of Markdown one of the syntax extensions defines Automatic generation of the table of contents:
* This will become a table of contents (this text will be scrapped).
{:toc}
This works in Maruku and kramdown.