Convert power

1

I have a function format(input) that transforms the code quotation of a numeric expression, to be in a more readable form for the user with unicode characters.

e.g. "3 * 2 + 1 - 5 / 2pi" -> "3 × 2 + 1 - 5 ÷ 2π"

However, with the potentiation, I want to make the number being elevated overwritten ( ¹²³ ), for this I used:

output = input.replace(/\s*\^\s*(\S+)/g, '<sup>$1</sup>');

REGEX: zero ou mais espaços, um ^, zero ou mais espaços, ( um ou mais não-espaços )

What works well for most cases where one number is being raised to another (e.g. x ^ 2 -> x² ). But if the number is raised to an expression (e.g. x ^ (2 - 6) ) it ends up having an error (because of the spaces) ...

So ... how do I turn the powers after ^ into superscript, at that time?

    
asked by anonymous 27.09.2017 / 04:09

2 answers

0

I believe this REGEX will solve your problem:

\s*\^\s*(\(.*.\)|\S+)
  • \ (. *. \) will match parentheses, and will group its contents.
  • OR followed by \ S + will look for non-whitespace characters.
  • Inputs / Outputs

    x ^ 2 -> x²              //x<sup>2</sup> -> x²
    x ^ (2 - 6)              //x<sup>(2 - 6)</sup>
    x ^ (2 - [6 + {x + y }]) //x<sup>(2 - [6 + {x + y }])</sup>
    x ^ y                    //x<sup>y</sup>
    3x ^ 7y                  //3x<sup>7y</sup>
    z ^ y2                   //z<sup>y2</sup>
    9 ^ √4                   //9<sup>√4</sup>
    9 ^ 30                   //9<sup>30</sup>
    2^1000000                //2<sup>1000000</sup>
    x ^ (2 - 1) + 3 - 5      //x<sup>(2 - 1)</sup> + 3 - 5
    

    Follow the tests link: link

        
    27.09.2017 / 04:43
    0

    Delete all spaces within parentheses in the string before applying <sup> :

    input = "2 ^ (2 - 6) + 5 ^ (2 + 3) - 6 ^ 10";
    input = input.replace(/\s+(?=[^(\]]*\))/g, "");
    output = input.replace(/\s*\^\s*(\S+)/g, '<sup>$1</sup>');
    

    input = "2 ^ (2 - 6) + 5 ^ (2 + 3) - 6 ^ 10";
    input = input.replace(/\s+(?=[^(\]]*\))/g, "");
    output = input.replace(/\s*\^\s*(\S+)/g, '<sup>$1</sup>');
    $("#teste").html(output);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste"></div>
        
    27.09.2017 / 04:45