How to regex replace from a showdown extension in js?

117 Views Asked by At

I am making a markdown (showdown js) extension for mathematics, expressions and plotting graphs. however I faced a problem here. I cannot replace a pattern by regex in the extension code, but I can replace it with the replace method!

what I've tried:

//load showdown module
// https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0
// i don't know how to load from js, i loaded from <script src="...">

// we replace {graph:<expression} into a div of class graph
function mathext(){
    return [{
        type:"lang",
        regex:/{graph:(.*)}/gi,
        replace:"<div class='graph'>$1</div>"
    }
];}
// load the extension
showdown.extension("mathext",mathext);

// create a converter
let converter = new showdown.Converter();

// make a function to convert markdown to html with pre-configured extension
function mathmd(md){
return converter.makeHtml(md);
}

// convert a ready markdown string to html.
let mathmds="# hello\n`x^2+y^2=9`\n##hello2\n{graph:x^2+y^2=9}";
document.getElementById("mathmd").innerText=mathmd(mathmds);

an html that runs this script looks like this:

<head>
<meta charset="utf-8">
<title>md</title>
</head>
<body>
<div id="mathmd"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0/showdown.min.js"></script>
<script src="mark.js"></script>
</body>
</html>

manual

Here is the manual replacement that correctly works:

let mathmds="# hello\n`x^2+y^2=9`\n##hello2\n{graph:x^2+y^2=9}";
let reg=/{graph:(.*)}/gi;
let toreplace="<div class='graph'>$1</div>"
alert(mathmds.replace(reg,toreplace));

Why does that happen? How to replace the pattern correctly? Thanks in advance.

0

There are 0 best solutions below