Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript RegEx for matching positive and negative integers [duplicate]

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"));
like image 414
user11229655 Avatar asked Dec 14 '22 11:12

user11229655


1 Answers

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"));
like image 61
Maheer Ali Avatar answered Dec 21 '22 10:12

Maheer Ali