Dylan Hobday Dylan Hobday - 5 months ago 15
HTML Question

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

I'm making a program where the user enters a fraction, then some JavaScript code will figure out the percentage of the given fraction.

For example, figure I enter 2/4, the program would return 50%.

I'm wondering if there's a function in JavaScript that will separate the numerator and denominator from the given value and make them into their own separate values. Here's my code so far:

HTML:

<!doctype html>
<html>
<head>
<title>Percentage finder JavaScript</title>
<link rel="stylesheet" href="styles/Index.css" />
</head>
<body>
<h1 id="Head">Enter your 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;

}

Answer

Assuming the user gives input as 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 a = +array[0];
    var b = +array[1];
    var result = 100 * (a / b) + '%'; // or just 100 * a / 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 just 100 * a / b
}