Mark Gerryl Mirandilla
Mark Gerryl Mirandilla

Reputation: 823

Javascript: Convert numbers inside the string

Im working on a simple conversation form, where I need to input dimensions ex. 12x24x36 inches to 304.8 x 609.6 x 914.4 mm.

My problem is I don't know how to compute convert those numbers separately.

I manage to remove the x but all the numbers merge.

Thanks, I hope you understand me.

here is my sample code

HTML

<h4>Dimensions</h4>
<label>inches <input id="number1"></label>
<label>mm <input id="number2"></label>
<button type="button" onclick="myFunction()">convert</button>

JS

function myFunction() {
var inches = document.getElementById("number1").value;

  var removex = inches.replace(/x/g,"");

  var input = parseInt(removex);

document.getElementById("number2").value = input
}

CODEPEN

https://codepen.io/anon/pen/yPpmej

Upvotes: 0

Views: 79

Answers (3)

user4513271
user4513271

Reputation:

EXPLANATION

You can convert your input example 12x24x36 into an array via str.split('x'), then do the math conversion from inch to millimeters (x inches * 25.4) and push those back into a new array of millimeters values. Then you can rejoin those values with an x via str.join('x') and put them back into your document. Here's what it looks like.

SCRIPT

function myFunction() {
  var inches = document.getElementById("number1").value.split('x');
  var millimeters = [];
  for (var i = 0; i < inches.length; i++) millimeters.push(parseInt(inches[i]*25.4));
  document.getElementById("number2").value = millimeters.join('x');
}

CODEPEN

https://codepen.io/anon/pen/KyZOYb

Upvotes: 1

Ronit Mukherjee
Ronit Mukherjee

Reputation: 405

If your receiving "12x24x36" as input(string) then for complete desired result update your function as below:-

function myFunction() {
  var inches = document.getElementById("number1").value;
  var inchesArr = inches.split("x");
  var mmArr = inchesArr.map(function(i) {
    return parseFloat(i) * 25.4;
  });
  var mmString = mmArr.join("x");

  document.getElementById("number2").value = mmString;
}

Upvotes: 1

Mark
Mark

Reputation: 92461

If you have a string like:

 var str = '304.8 x 609.6 x 914.4 mm'

You can use split() and parseFloat() to get an array of numbers with:

var str = '304.8 x 609.6 x 914.4 mm'
var numbers = str.split('x').map(parseFloat)
console.log(numbers)

You just need to know your input format so you can adjust for other variations.

parseFloat() will ignore any non-numeric characters after the numbers so it works well for stripping units.

Upvotes: 3

Related Questions