javascript - How would I go about separating numbers in a string and making them their own values? -


i'm making program user enters fraction, javascript code figure out percentage of given fraction.

for example, figure enter 2/4, program return 50%.

i'm wondering if there's function in javascript separate numerator , denominator given value , make them own separate values. here's code far:

html:

    <!doctype html>  <html>    <head>       <title>percentage finder javascript</title>       <link rel="stylesheet" href="styles/index.css" />    </head>    <body>       <h1 id="head">enter fraction:</h1>       <form>          <input id="fraction" autofocus="on" placeholder="i.e: 1/4"></input>          <input type="submit" id="sbmt"></input>        </form>    </body>    <script src="scripts/js/index.js" type="text/javascript"></script> </html> 

javascript:

document.getelementbyid('sbmt').onclick = function() {  var x = document.getelementbyid('fraction').value;  } 

assuming user gives input value_1 / value_2, without parentheses, multiplication signs etc...:

document.getelementbyid('sbmt').onclick = function() {     var value = document.getelementbyid('fraction').value;     var array = value.split(/\//);     var = +array[0];     var b = +array[1];     var result = 100 * (a / b) + '%'; // or 100 * / b } 

es6:

document.getelementbyid('sbmt').onclick = function() {     const value = document.getelementbyid('fraction').value;     const [a, b] = value.split(/\//).map(x => +x);     const result = 100 * (a / b) + '%'; // or 100 * / b } 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -