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.

nicael
  • 18,550
  • 13
  • 57
  • 90
Nastya Gorobets
  • 197
  • 2
  • 10
  • 23

2 Answers2

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.

nicael
  • 18,550
  • 13
  • 57
  • 90
  • Except this returns an array of strings, not integers. – Andy Dec 20 '15 at 12:05
  • @Andy okay, edited. This doesn't really matter though, they can be converted on fly... – nicael Dec 20 '15 at 12:07
  • 2
    You can also also do [`var numbers = str.match(/\d+/g).map(Number);`](https://jsfiddle.net/andyuws/46dofdev/). – Andy Dec 20 '15 at 12:20
  • Or use parseInt instead. See http://stackoverflow.com/questions/4564158/what-is-the-difference-between-parseintstring-and-numberstring-in-javascript – roland Dec 20 '15 at 12:36
  • @roland where would you suggest to put `parseInt`? I'm converting to number with `+`, seems to be shorter. – nicael Dec 20 '15 at 12:37
  • `var str = '';` or anything without a match, `for` or `map` will fail. – Xotic750 Dec 20 '15 at 12:41
  • You do realise that `a` is a global variable as you have not declared it? – Xotic750 Dec 20 '15 at 17:14
  • @Xotic Of course I do. I don't care though, how is it a problem? – nicael Dec 20 '15 at 17:18
  • A quote from David Walsh - `Leaking global variables is bad practice and a result of sloppy coding. `. No problem for me, it's a practice that I avoid. – Xotic750 Dec 20 '15 at 17:52
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.

Xotic750
  • 22,914
  • 8
  • 57
  • 79