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,939
  • 14
  • 56
  • 110

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
  • 157,677
  • 23
  • 242
  • 245
  • 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
  • 384,651
  • 66
  • 527
  • 531
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
  • 10,060
  • 5
  • 44
  • 88
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,817
  • 19
  • 86
  • 129