Search code examples
javascriptarraysstringsplitmathjax

Javascript split with substring and include said substring in the produced array


I'm leveraging MathJax for a solution I'm building. I'm using a placeholder—\Box—for a facts family equation. I want to replace this placeholder when a solution based on a user's input.

Okay, so my question, given strings like these:

  • "\begin{array}{r} \Box\\ - \quad 7\\ \hline 6\end{array}"
  • "\begin{array}{r} 12\\ - \quad \Box\\ \hline 1\end{array}"
  • "\begin{array}{r} \Box\\ + \quad 1\\ \hline 6\end{array}"
  • etc.

\Box can show up in different spots in the string as you can see.

The Goal

I would like to evaluate the MathJax string and find \Box. Once I find it I want to split at that point and then build an array that also includes \Box as one of the items in the array at the point for which it was found.

Desired Outcome

// With this string
    str = "\begin{array}{r} 12\\ - \quad \Box\\ \hline 1\end{array}"

// Find and split on '/Box' and include it.

// Desired Output
    ["\begin{array}{r} 12\\ - \quad ", "\Box", "\ \hline 1\end{array}"]

Any ideas would be much appreciated.

Thank you in advance!


Solution

  • Try to split it using regular expression

    str.split(/(\\Box)/);
    

    The parentheses will do the trick.