pram pram - 2 months ago 11
HTML Question

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>




Answer

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 i.e. $1 and wrap $2 around { and }.