0

I have a string likes

AA-12,AB-1,AC-11,AD-8,AE-30

I want to get number only from this string likes

12,1,11,8,30

How can I get this using JavaScript ? Thanks :)

zey
  • 5,803
  • 14
  • 53
  • 100

4 Answers4

6

Use a regex, eg

var numbers = yourString.match(/\d+/g);

numbers will then be an array of the numeric strings in your string, eg

["12", "1", "11", "8", "30"]
Phil
  • 141,914
  • 21
  • 225
  • 223
  • Looks like you forget about join with comma separator – Maxim Zhukov Jul 16 '13 at 05:15
  • @FSou1 I forgot nothing. An array is much easier to work with and can be transformed into a comma delimited string easily enough using `numbers.join(',')` – Phil Jul 16 '13 at 05:18
1

Also if you want a string as the result

'AA-12,AB-1,AC-11,AD-8,AE-30'.replace(/[^0-9,]/g, '')
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
1
var t = "AA-12,AB-1,AC-11,AD-8,AE-30";
alert(t.match(/\d+/g).join(','));

Working example: http://jsfiddle.net/tZQ9w/2/

Maxim Zhukov
  • 9,875
  • 5
  • 39
  • 82
1

if this is exactly what your input looks like, I'd split the string and make an array with just the numbers:

var str = "AA-12,AB-1,AC-11,AD-8,AE-30";
var nums = str.split(',').map(function (el) {
    return parseInt(el.split('-')[1], 10);
});

The split splits the string by a delimiter, in this case a comma. The returned value is an array, which we'll map into the array we want. Inside, we'll split on the hyphen, then make sure it's a number.

Output:

nums === [12,1,11,8,30];

I have done absolutely no sanity checks, so you might want to check it against a regex:

/^(\w+-\d+,)\w+-\d+$/.test(str) === true

You can follow this same pattern in any similar parsing problem.

beatgammit
  • 19,051
  • 16
  • 83
  • 125