//md:
# h1
## h2
//out:
<h1 id="h1">h1</h1>
<h2 id="h2">h2</h1>
//md:
# h1
# h1
//out:
<h1 id="h1">h1</h1>
<h1 id="h1">h1</h1>
//md:
# 这行只有汉字
# 这行也是
//out:
<h1 id="-">这行只有汉字</h1>
<h1 id="-">这行也是</h1>
//md:
## 这行只有汉字
## 这行也是
//out:
<h2 id="-">这行只有汉字</h1>
<h2 id="-">这行也是</h1>
I have a same problem...
I solved this by overriding marked.Renderer#heading function.
const renderer = new marked.Renderer();
renderer.heading = function(text, level) {
return `<h${level} id="${text}">${text}</h${level}>`;
};
marked(mdString, { renderer: renderer });
It seems to be natural to assume the above-mentioned behavior is a specification.
I do it:
The full code is here
var ID_TABLE = "0123456789ABCDEF";
var AUTOID = 0x0001;
...
Renderer.prototype.heading = function(text, level, raw) {
var id, tmp;
tmp = AUTOID++;
id = ID_TABLE.charAt((tmp >> 12) & 0x0F);
id += ID_TABLE.charAt((tmp >> 8) & 0x0F);
id += ID_TABLE.charAt((tmp >> 4) & 0x0F);
id += ID_TABLE.charAt(tmp & 0x0F);
return '<h'
+ level
+ ' id="'
+ id
// + this.options.headerPrefix
// + raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
There's no perfect way to generate IDs. The "naive" way to fix this would be to add a numeric counter to duplicate IDs, but that would require keeping track of all IDs.
I still think the easiest way is to not have Marked do it. This is what I used to do back in the day for scrolling table of contents a la Bootstrap - http://getbootstrap.com/2.3.2/getting-started.html
Step one: Convert Markdown to HTML.
Step two (DOM is ready/loaded): Cycle through the headers to add ID attributes and generate the TOC in one shot.
No JS solution = no TOC; therefore, no reason to have the IDs in the first place.
Again, could just be asking Marked to do too much. If a spec has it, we should too but, if a spec has it, it should define the testable rules for implementing the solution, yeah?
Note: I did not use Marked for processing back in the day.
@tagia0212
if your header includes (), it will failure. eg:
### do something()
Closing as most likely going to be deprecated at a later date.
The problem still exists.
Yes, this problem still exists.
Let's consolidate this issue with a similar one here: #1280
Sidenote: GitHub adding detail popovers on hover...fancy. 😎
Most helpful comment
I solved this by overriding
marked.Renderer#headingfunction.It seems to be natural to assume the above-mentioned behavior is a specification.