Home > Software design >  How to parse a custom id from within a markdown heading?
How to parse a custom id from within a markdown heading?

Time:08-10

I want to parse a custom id from a markdown heading. For instance, #hello-world from #this is a heading {#hello-world}.

This regex I tried does not seem to work:

const regExp=/#{1,6}\s .*\{(?<id>.*)\}/g

CodePudding user response:

Try this :

let text = "#hello-world"
let id = text.match(/#{1,6}([\s\WA-z0-9] )/g).pop()
console.log(`#this is a heading {${id}}`)

CodePudding user response:

To get your match, you could use a capture group

{(#{1,6}\w (?:-\w )*)}

Explanation

  • { Match the opening {
  • ( Capture group 1
    • #{1,6} Match 1-6 times #
    • \w Match 1 word chars
    • (?:-\w )* Optionally repeat - and 1 word chars
  • ) Close group 1
  • } Match the closing }

See a regex demo

const regex = /{(#{1,6}\w (?:-\w )*)}/;
const str = `#this is a heading {#hello-world}`;
const m = str.match(regex);
if (m) console.log(m[1]);

Or the bit broader match, with named group id

{(?<id>#{1,6}[^{}]*)\}

Regex demo

  • Related