admin管理员组

文章数量:1289351

I have a string like below

Original string  : results

1apple23oranges  : 1 , 23

4apples1oranges  : 4, 1

25oranges        : 25

By regular expression or any, i can't figure out how to get the above results as pure digits in javascript.

Any idea pls?

I have a string like below

Original string  : results

1apple23oranges  : 1 , 23

4apples1oranges  : 4, 1

25oranges        : 25

By regular expression or any, i can't figure out how to get the above results as pure digits in javascript.

Any idea pls?

Share Improve this question edited May 10, 2011 at 6:58 kapa 78.7k21 gold badges165 silver badges178 bronze badges asked May 10, 2011 at 6:55 Kathy001Kathy001 11 gold badge1 silver badge1 bronze badge
Add a ment  | 

4 Answers 4

Reset to default 7

Use the regular expression \d+, which means any digit from 0 to 9 (\d) repeated one or more times (+). The qualifier g will make the search global (ie: don't stop on the first hit).

resultArray = original.match(/\d+/g);

This will result an array with all the numbers, to join them using ", " a separator, use the function join()

resultString = original.match(/\d+/g).join(", ");
'1apple23oranges'.match(/\d+/g);

Use match function on your string object with expression .match(/\d+/g).

Eg. var a = "1apple23oranges"

 var res = a.match(/\d+/g)

You can separate each values by ma.

Try "1apple23oranges".match(/(\d+)/g);

Note: If you need the digits as integer value then you have to use parseInt for that. If you are using jQuery then you can have all the integers in an array

var arr = new Array(); 
$.each("1apple23oranges".match(/(\d+)/g), function(index, value){ arr.push(parseInt(value, 10));});

本文标签: regexJavascriptExtracting the digits from different positions from a stringStack Overflow