Dylan Hobday Dylan Hobday - 1 year ago 68
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:


<!doctype html>
<title>Percentage finder JavaScript</title>
<link rel="stylesheet" href="styles/Index.css" />
<h1 id="Head">Enter your fraction:</h1>
<input id="fraction" autofocus="on" placeholder="i.e: 1/4"></input>
<input type="submit" id="sbmt"></input>
<script src="Scripts/js/Index.js" type="text/javaScript"></script>


document.getElementById('sbmt').onclick = function() {

var x = document.getElementById('fraction').value;


Answer Source

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download