-1

items: "Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4"

function shoppingList(items) {
    var split = items.split("");
    var nums = split.filter(x => x != (/[a-z]+/gi));
    console.log(nums);
}

I want to make this function filter out anything other than the numbers, including the ones with a decimal point. Is there a way to do this with a regex expression? I tried to make one, but either the regex is wrong, or something with my .filter() method. The end goal is to put all of the numbers in an array.

Console output:

[
  'D', 'o', 'u', 'g', 'h', 'n', 'u', 't',
  's', ',', ' ', '4', ';', ' ', 'd', 'o',
  'u', 'g', 'h', 'n', 'u', 't', 's', ' ',
  'h', 'o', 'l', 'e', 's', ',', ' ', '0',
  '.', '0', '8', ';', ' ', 'g', 'l', 'u',
  'e', ',', ' ', '3', '.', '4'
]
  • 1
    `x != (/[a-z]+/gi)` will not check `x` against the regex, it will check if `x` is *not* the regex. As in is `x` not the literal RegExp object. You need to use [`RegExp#test`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) to see if a regex matches something or not. – VLAZ Sep 12 '20 at 18:37
  • 3
    What's your expected result? Especially, if you have an input text like `Doughnuts,17;` – derpirscher Sep 12 '20 at 18:37

1 Answers1

1

One way to do this:

console.log(
   'Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4'
   .match(/[+-]?\d+(?:\.\d+)?/g)
); 

If you need an array of numbers, you can apply .map and parse the string values as numbers:

const numberArr = 'Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4'
.match(/[+-]?\d+(?:\.\d+)?/g)
.map(a => Number(a))

console.log(numberArr);
eol
  • 23,236
  • 5
  • 46
  • 64