I am trying to extract positive and negative integers from the given string. But able to extract only positive integers.
I am passing "34,-10" string into getNumbersFromString param
I am getting
Output:
['34','10']
The expected output should be
[34,-10]
How do I solve this problem?
function getNumbersFromString(numberString){
  var regx = numberString.match(/\d+/g);
  return regx;
}
console.log(getNumbersFromString("34,-10"));
You can also match the -sign(at least 0 and at most 1) before the number. Then you can use map() to convert them to number.
function getNumbersFromString(numberString){
  var regx = numberString.match(/-?\d+/g).map(Number);
  return regx;
}
console.log(getNumbersFromString("34,-10"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With