0

I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"

I think that I can do it how this:

var ax = data.split('(');
var ax2 = ax[1].split(')');

ax2[0] has "341"

Now If I can repeat this but starting in the next indexOf to take the second number.

I think that it's a bad practice, so I ask you If you have a better idea.

Thanks in advance

oscarvady
  • 450
  • 1
  • 4
  • 12
  • use regexp see here http://stackoverflow.com/questions/13807207/regex-find-a-number-between-parentheses – Mritunjay Aug 29 '14 at 10:23

3 Answers3

4

Use a regular expression:

var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]

Now you can just access the numbers in the array as normal.

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
1

You can use regex to extract all numbers from this.

var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);

Here ax is now ["341", "20", "3131"]

Note that ax contains numbers as string. To convert them to number, use following

ax2 = ax.map( function(x){ return parseInt(x); } )

EDIT: You can alternatively use Number as function to map in the line above. It'll look like,

ax2 = ax.map( Number )

After this ax2 contains all the integers in the original string.

nisargjhaveri
  • 1,469
  • 11
  • 21
0

You could use a regular expression, eg:

var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;

var result = string.match(pattern);
console.log(result);
//  ["341", "20", "3131"]

http://regex101.com/r/zE9pS7/1

SubjectCurio
  • 4,702
  • 3
  • 32
  • 46