How to retrieve id from a heading and apply it as collapse class to non-headings

special characters** are invalid If IRC

So anything that is not a letter, number, dash, or underscore ( _ )? or just not letters or numbers?

More like the first but I think here’s the correct answer, hence the regex I should had used.

Will try that and report back.
Update: I will go removing anything that could potentially be problematic

The goal should be to generate valid id values and removing anything that could potentially be problematic. The above regex accepted answer doesn’t seem to work neither.
var id = $heading.getAttribute("id") || $heading.innerText.toLowerCase().replace(/^[^a-z]+|[^\w:.-]+/g, '').replace(/ +/g, '-');

Question: even for a simple name or generated id it is not generating the collapse-class… so may the problem be somewhere else as well?

Can you put your full project code in something like Codepen, so we do not have to keep copying/pasting or wondering if we have the full latest version of your code?

It would make it easier for us to test and give guidance.

Thank you.

How is the above code related to the other code?

This generates the ids for each header which are then used to generate the classes for every sibling that is not a header

Would it do if I rather just publish this on my website? it is meant to be a CSS guide…

Thank to everyone. I figured out, I had to wrap both codes inside window.onload function for it to properly load.