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
1 Answer
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)
gmodifier: 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);
5 Comments
31piy
if no number found then value of a and b will be 0 -- This will not be handled by this code.
Deepak Jain
for 50001000 amount string 50001000undefined is coming dor document.write
Satpal
@Shrey,
50001000 is a single numberDeepak Jain
@Satpal what is there is only 1 number or no number at all ?
Satpal
@AkhilJain, no number at all
arr will be null otherwise arr will have integers 1,2,3 whatever is present in string
string.match(/\d+/g).map(Number);