Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5973
  • Last Modified:

Get the number value from string

How do I get the value of a number from a string in Javascript? Like with 'ABC12' I just want to return the 12.
0
niner
Asked:
niner
  • 2
1 Solution
 
dakydCommented:
As a very basic example, this should do what you want:

<script type="text/javascript">
var str = "ABC12g";
str = str.replace(/\D/g,"");
alert(str);
</script>

You can replace str with whatever variable you use.  The one potential problem is if you have more than one number in the string (e.g., "a1b2c"), it'll strip out all the letters and then return all the numbers.  So, if you gave it "a1b2c", it'd alert "12", instead of "1" or "2".  Is that okay?
0
 
dakydCommented:
<Sorry, should've included this in the first post>

If you want to only get the first number/decimal in the string, you can use the following:

<script type="text/javascript">
var str = "ABC12g345";
str = parseFloat(str.replace(/^\D+/,""));
alert(str);
</script>

The regular expression will strip out any non-numbers in the beginning of the string, and then take the numbers left at the beginning.  Hope one of the two helps.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now