1

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

2
  • 3
    string.match(/\d+/g).map(Number); Commented Jul 19, 2018 at 6:10
  • have a look at this replace all alphabets from string Commented Jul 19, 2018 at 6:10

1 Answer 1

5

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);

Sign up to request clarification or add additional context in comments.

5 Comments

if no number found then value of a and b will be 0 -- This will not be handled by this code.
for 50001000 amount string 50001000undefined is coming dor document.write
@Shrey, 50001000 is a single number
@Satpal what is there is only 1 number or no number at all ?
@AkhilJain, no number at all arr will be null otherwise arr will have integers 1,2,3 whatever is present in string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.