Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get a number value of a string in Javascript?
To extract numeric values from strings in JavaScript, you have several approaches depending on your needs. The most common methods are using regular expressions with parseInt(), parseFloat(), or Number().
Using parseInt() with Regular Expression
For extracting integers from strings containing mixed content, combine parseInt() with match() and a regex pattern:
<!DOCTYPE html>
<html>
<body>
<script>
var myStr = "abcdef 30";
var num = parseInt(myStr.match(/\d+/));
console.log("Extracted number:", num);
console.log("Type:", typeof num);
</script>
</body>
</html>
Extracted number: 30 Type: number
Using parseFloat() for Decimal Numbers
When dealing with decimal numbers, use parseFloat() instead:
<!DOCTYPE html>
<html>
<body>
<script>
var myStr = "price: $45.99";
var num = parseFloat(myStr.match(/\d+\.?\d*/));
console.log("Extracted decimal:", num);
</script>
</body>
</html>
Extracted decimal: 45.99
Using Number() for Pure Numeric Strings
For strings that contain only numbers (with optional whitespace), use Number():
<!DOCTYPE html>
<html>
<body>
<script>
var str1 = "123";
var str2 = " 456.78 ";
console.log("String '123':", Number(str1));
console.log("String ' 456.78 ':", Number(str2));
console.log("Invalid string 'abc':", Number("abc"));
</script>
</body>
</html>
String '123': 123 String ' 456.78 ': 456.78 Invalid string 'abc': NaN
Extracting All Numbers from a String
To extract all numeric values from a string:
<!DOCTYPE html>
<html>
<body>
<script>
var myStr = "I have 5 apples and 3.5 oranges";
var numbers = myStr.match(/\d+\.?\d*/g);
console.log("All numbers found:", numbers);
console.log("As numeric values:", numbers.map(Number));
</script>
</body>
</html>
All numbers found: ["5", "3.5"] As numeric values: [5, 3.5]
Comparison of Methods
| Method | Best For | Handles Decimals | Mixed Content |
|---|---|---|---|
parseInt() |
Integers only | No | With regex |
parseFloat() |
Decimal numbers | Yes | With regex |
Number() |
Pure numeric strings | Yes | No |
Conclusion
Use parseInt() with regex for extracting integers from mixed content, parseFloat() for decimals, and Number() for converting pure numeric strings. Always handle potential NaN results when dealing with invalid input.
