简体   繁体   中英

How to regex match and replace to katex

updated

 function test() { var text = "3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i 50 50 3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i [x = - -----------------, x = -----------------] 50 50 3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i 50 50i"; var alter = text.replace("()","{}").replace(/(\\d+)?([sqrt])/g,"\\\\");//i need a answer 3\\\\sqrt{11} alert(alter); katex.render(alter, document.getElementById('demo')); } test();
 <script src="https://khan.github.io/KaTeX/bower_components/katex/dist/katex.min.js"></script> <link href="https://khan.github.io/KaTeX/bower_components/katex/dist/katex.min.css" rel="stylesheet"/> <p id="demo"></p>

I have string 3sqrt(11) in match and replace using regex .Because i was get the output via katex formet. I was tried with below script:

 function test() { var text = "3sqrt(11)"; var alter = text.replace("()","{}").replace(/(\\d+)?([sqrt])/g,"\\\\");//i need a answer 3\\\\sqrt{11} alert(alter); katex.render(alter, document.getElementById('demo')); } test();
 <script src="https://khan.github.io/KaTeX/bower_components/katex/dist/katex.min.js"></script> <link href="https://khan.github.io/KaTeX/bower_components/katex/dist/katex.min.css" rel="stylesheet"/> <p id="demo"></p>

You can do this in a single .replace call using captured groups:

 function test() { var text = "3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i 50 50 3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i [x = - -----------------, x = -----------------] 50 50 3 sqrt(11) %i - 1 1 + 3 sqrt(11) %i 50 50i"; var alter = text.replace(/(\\d+)\\s*(sqrt)\\((\\d+)\\)/g, "$1\\\\\\\\$2{$3}") console.log(alter); } test();

Here in 1st group we are matching & capturing sqrt . In 2nd group we are matching ( followed by some number followed by ) .

Then in replacement we add \\\\ before 1st group backreference ie $1 and wrap $2 around { and } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM