Q: Splitting a string and wrapping math tags in that string I have a string that contains math. I need to wrap the math tags in a span and put the string back together. I have accomplished this for a specific case but I am looking for something far simpler(if there is) and a more efficient way to accomplish this. For instance if there is text before the math Tag this would not work or if there are multiple math tags this would not work. Thanks for any help you can give.
String
<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math> I am text after the string.

Desired String
<span class="math math-inline"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math></span> I am text after the string.

Solution So far
let spanStart = '<span class="math math-inline">';
let spanEnd = '</span>';
let mathStart = '<math';
let mathEnd = '</math>';
let startPos = mathString.indexOf(mathStart);
let endPos = mathString.indexOf(mathEnd);

let output = mathString.substr(startPos, 0) + spanStart + mathStart + mathString.substr(mathStart.length, (endPos - mathStart.length)) + mathString.substr(endPos, mathEnd.length) + spanEnd + mathString.substr((endPos + spanEnd.length));

I have made a pen to show my solution so far but again it will not work all the time.
For instance if had:
This is question 2 <math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math> I am text after the string.

It would not longer be correct. Thanks for your help

A: Assuming that the <math> tag is within the <body>. Use .innerHTML.


var html = document.querySelector('body').innerHTML;
document.querySelector('body').innerHTML = `<span class='math math-inline'>${html}</span>`;
.math {font-family: consolas; font-style:italic; color:red}
<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math>



A: Here is my solution based off of @Lewsi comment
function wrapMath (string) {
  if (typeof string !== 'string') return false
  if (!checkForMath(string)) return false

  const spanStart = '<span class="math math-inline">'
  const spanEnd = '</span>'

  return string.replace(/<math/g, spanStart + '<math').replace(/<\/math>/g, spanEnd)
}

let string = 'This is my string <math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math> I am text after the string.
'

wrapMath(string)

// Output
'This is my string <span class="math math-inline"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#xA0;</mo><msqrt><mn>34</mn></msqrt></math></span> I am text after the string'

