jhnferraris
jhnferraris

Reputation: 1401

Javascript: How to extract measurements in a string

I'm trying to extract measurements in a string.

This is my current approach:

const string = '10mL 5mL';
const regex = `([0-9]*mL)|([0-9]*g)|([0-9]*gallon)|([0-9]*kg)|([0-9]*L)|([0-9]*mg)|([0-9]*patches)`;
console.log(string.matches(regex));

So I'm expecting that the output would be ['10mL', '5mL']. When I check the logs it only extracts the first 10mL

[ '10mL',
  '10mL',
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  index: 0,
  input: '10mL 5mL',
  groups: undefined ]

Any tips on what I am missing here? Thank you!

Upvotes: 1

Views: 175

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

The function you are looking for is match and not matches. Also you can write your regex in a compact form like this,

/(\d+\s*(?:mL|g|gallon|kg|L|mg|patches))/g

Try this JS code,

const string = '10mL 5mL 25 mL';
const regex = /(\d+\s*(?:mL|g|gallon|kg|L|mg|patches))/g;
console.log(string.match(regex));

Sure Timothy Hawkins, you can replace \d+ with \d+(\.\d+)? in the regex and it would capture decimal numbers too.

Demo is following,

const string = '10mL 5mL 25 mL 12.5kg, 5.2mL';
const regex = /(\d+(\.\d+)?\s*(?:mL|g|gallon|kg|L|mg|patches))/g;
console.log(string.match(regex));

Sorry for the delay in replying, not mostly active as loaded with too much work :(

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521179

Try matching the regex pattern \d+\s*\w+ multiple times:

var re = /\d+\s*\w+/g;
var input = '10mL 5mL';
var m;
var output = [];

do {
    m = re.exec(input);
    if (m) {
       output.push(m[0]);
    }
} while (m);

console.log(output);

Upvotes: 3

Related Questions