Shaun Williams
Shaun Williams

Reputation: 1

Seperate Numeric Whole,Decimal and/or Fraction from start of string in Javascript

Basically, I am trying to separate the amounts from their respective measurements for a list of recipes. This is so I can adjust amounts based on the number of serve's needed. I have the calculations working but still trying to edit the string to use in the math in the JavaScript.

Here is a list of possible values with the value I actually need in first bracket. But I also need to keep the measurement shown in second bracket.

The problem I have is the amount and measurement are in the same DB field and I cannot separate them in the back end without breaking allot of the original code. Also, any updates to the code by its author will mean I have to recode it. So any help on getting the right values would be much appreciated.

Upvotes: 0

Views: 40

Answers (1)

jcubic
jcubic

Reputation: 66488

You can use regular expressions:

var input = [
  '1g (1) (g)',
  '1 g (1) (g)',
  '1/2cup (0.5) (cup)',
  '1/2 cup (0.5) (cup)',
  '1 1/2cup (1.5) (cup)',
  '1 1/2 cup (1.5) (cup)',
  '2.5g (2.5) (g)'];
function extract(item) {
  return item.match(/\(([^\)]+)\) \(([^\)]+)\)/).slice(1);
}
var output = input.map(extract);
document.getElementById('output').innerHTML = JSON.stringify(output);
<pre id="output"></pre>

Upvotes: 2

Related Questions