Deepak Jain
Deepak Jain

Reputation: 137

how to identify and store number in variables present in String in JavaScript?

let's say i have a string in format like
1."Amount is between 5000 and 10000"
2. "Amountbetween5000 and10000"
3."5000 Amountbetweenand10000"
4."50001000 amount"

then i need to store 5000 and 10000 in 2 variables let's say a and b
if no number found then value of a and b will be 0
string can or cannot have space between Words

Upvotes: 1

Views: 126

Answers (1)

Satpal
Satpal

Reputation: 133453

You can use Regular Expressions

var numbers = string.match(/\d+/g).map(Number);

\d+ matches a digit (equal to [0-9])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

g modifier: global. All matches (don't return after first match)

Here in example, handled case if no match is found.

var string = "Amount is between 5000 and 10000",
  numbers = [];

var arr = string.match(/\d+/g);
if (arr != null)
  numbers = arr.map(Number)

console.log(numbers);

Upvotes: 5

Related Questions