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 :)

0

4 Answers 4

7

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

Looks like you forget about join with comma separator
@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(',')
1

Also if you want a string as the result

'AA-12,AB-1,AC-11,AD-8,AE-30'.replace(/[^0-9,]/g, '')

Comments

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/

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.