0

I have string such as 12 3 44 5 \n 7 88 I want get from string only numbers and write them in array: [12,3,4,5,7,88]. I want do it whith RegExp:

  var str='12  3   44 5 \n 7 88';
  alert(str);
  var re =/^\S+$/;
  var res=re.exec(str);
  alert(res[0]);
  alert(res[1]);
  alert(res[2]);

But it doesn't work for me.

1

2 Answers 2

4

Correct way:

var str = '12  3   44 5 \n 7 88';
//if there matches, store them into the array, otherwise set 'numbers' to empty array
var numbers = str.match(/\d+/g)?str.match(/\d+/g):[];
//to convert the strings to numbers
for(var i=0;i<numbers.length;i++){
    numbers[i]=+numbers[i]
}
alert(numbers);

Why? .match() is just an easier thing to use there. \d+ gets a number of any length, flag g returns all the matches, not only the first match.

If you also want to match the floats, the regex would be /\d+([\.,]\d+)?/g. It'll also match 42,12 or 42.12.

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

9 Comments

Except this returns an array of strings, not integers.
@Andy okay, edited. This doesn't really matter though, they can be converted on fly...
Or use parseInt instead. See stackoverflow.com/questions/4564158/…
@roland where would you suggest to put parseInt? I'm converting to number with +, seems to be shorter.
|
1

A possible alteranative

var s = '12  3   44 5 \n 7 88';
var numbers = s.split(/[^\d]+/).map(Number);

document.getElementById('out').textContent = JSON.stringify(numbers);
console.log(numbers);
<pre id="out"></pre>

With split you will never have a situation like where exec or match could be null

Note: this does not take into account negative numbers or floating point or scientific numbers etc. An empty string will also produce [0], so specification is key.

Comments

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.