Home > Software design >  .exec() Regex only works when I console.log it
.exec() Regex only works when I console.log it

Time:02-27

So I was trying to make a markdown parser that supports tailwinds but got stuck on the code block part. whenever I run .exec() on the code block regex I can't access the values from the returned array, I can only log the array to console. I also tried adding a lastIndex but that doesn't work.

function parseCodeBlock(data) {
  let match = /^(([ \t]*`{3,4})([^\n]*)([\s\S] ?)(^[ \t]*\2))/gm.exec(
    data.string
  );
  return JSON.parse(JSON.stringify(match));
}
// line 94 - 97
let match = parseCodeBlock({ string: HtmlCode });
console.log(match);
let code = match[3];

enter image description here

CodePudding user response:

From the logs, your code is executed twice, the second time the returned value is null.

Note: I tried to add this as comment but I don't have enough reputation points as a new contributor :)

CodePudding user response:

As I can see from your screenshot, there are two logs from the same code line (95). One with the array, the second with null.

I guess you're trying to access the array AFTER the second log (null)

CodePudding user response:

I found another regex that fixed this problem here is the code.

function parseCodeBlock(data) {
  let html = data.string.replace(
    /^```(([a-z0-9-] ?)\n )?\n*([^] ?)\n*```/gim,
    `<pre><code >$3</code></pre>`
  );
  return html;
}
  • Related