Hello!

I have a div and input block. When the user enters a value into input , this value is transferred to the div . How can I do that when a user enters, for example, a degree ( 2^3 ), then it was displayed in a div'е like this: ?

Code:

 $(function() { $('#number').on('keyup', function() { $('#value').html($(this).val()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <input type="text" id="number"> </p> <p>Уравнение:</p> <div id="value"></div> 

  • $('#value').html(process($(this).val())); where process is your conversion - vp_arth
  • @vp_arth, and what is the process ? - user238662
  • A function of the form string => string , in which you parse the field value, and build what you want to see. - vp_arth
  • @vp_arth, so I don’t understand how to parse it and output what I want - user238662

1 answer 1

$('#value').html(process($(this).val())); where process is your conversion:

 $(function() { $('#number').on('keyup', function() { $('#value').html(process($(this).val())); }); }); function process(str) { return str.replace(/\^(\d+)/g, '<sup>$1</sup>'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <input type="text" id="number"> </p> <p>Уравнение:</p> <div id="value"></div> 


There is no support for recursive regular expressions in Javascript , so you need to either write a parser or pervert.
Without nested brackets, you can:

 $(function() { $('#number').on('keyup', function() { $('#value').html(process($(this).val())); }); $('#value').html(process($('#number').val())); }); function process(str) { var res; while (res !== str) { res = str; str = res.replace( /([^+\-*/\^()]+)\^([^+\-*/\^()]+|\([^\)]+\))/g, '$1<sup>$2</sup>' ); } return str; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <input type="text" id="number" value="a^(x^3+3^x)/x^2"> </p> <p>Уравнение:</p> <div id="value"></div> 

  • And if I enter 2 ^ (3 ^ 5), it will not output - user238662
  • I do not plan to write an expression parser for you. Sorry. - vp_arth
  • Thank. Thought it out. Never been friends with regular expressions :) - user238662