How can I check if a string is a valid number?
2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".
":
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
isNaN(num) // returns true if the variable does NOT contain a valid number
Examples
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
Of course, you can negate this if you need to. For example, to implement the IsNumeric
example you gave:
function isNumeric(num){
return !isNaN(num)
}
To convert a string containing a number into a number:Only works if the string only contains numeric characters, else it returns NaN
.
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
Examples
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
To convert a string loosely to a numberUseful for converting '12px' to 12, for example:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
Examples
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
FloatsBear in mind that, unlike +num
, parseInt
(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt()
because of this behaviour, you're probably better off using another method instead):
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
Empty stringsEmpty strings may be a little counter-intuitive. +num
converts empty strings or strings with spaces to zero, and isNaN()
assumes the same:
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
But parseInt()
does not agree:
parseInt('') // NaN
parseInt(' ') // NaN
Check whether an input string contains a (signed) number
You can easily use a regex expression to match the numbers in the string:
function f2(input) { let str = String(input); let result = str.match(/\-?\d+\.\d+|\-?\d+/g) return result } let result = f2("a1 12 13.b -14.5+2"); console.log(result);
Check if string contains only digits
how about
let isnum = /^\d+$/.test(val);
Check whether variable is number or string in JavaScript
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true
for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
Check if string contains number? If yes then replace that number with another string
You can use string replace() for this, pass a required regex to fit your requirement.
let myString = "/example/123/anotherstring" let newString = myString.replace(/\d+/g, "replaced")console.log(newString)
myString = "/example/anotherstring/123" newString = myString.replace(/\d+/g, "replaced") console.log(newString)
How to check if String has a Number?
function hasNumber( str ){
return /\d/.test( str );
}
results:
hasNumber(0) // true
hasNumber("0") // true
hasNumber(2) // true
hasNumber("aba") // false
hasNumber("a2a") // true
While the above will return truthy as soon the function encounters one Number \d
if you want to be able return an Array of the matched results:
function hasNumber( str ){
return str.match( /\d+/g );
}
results:
hasNumber( "11a2 b3 c" ); // ["11", "2", "3"]
hasNumber( "abc" ); // null
if( hasNumber( "a2" ) ) // "truthy statement"
where +
in /\d+/g
is to match one or more Numbers (therefore the "11" in the above result) and the g
Global RegExp flag is to continue iterating till the end of the passed string.
Advanced_Searching_With_Flags
RegExp.prototype.test()
String.prototype.match()
Related Topics
Regex to Allow Only Certain Special Characters and Restrict Underscore
How to Include External JavaScript Library in Reactjs
Angular 2 Concatenate Variable in Interpolation
How to Open Hidden Information on Website
The Create-React-App Imports Restriction Outside of Src Directory
How to Show Roles of User Discord.Js/Userinfo Command
Easiest Way to Open a Download Window Without Navigating Away from the Page
Javascript File Not Updating No Matter What I Do
Convert 12-Hour Hh:Mm Am/Pm to 24-Hour Hh:Mm
How to Get Only First Character Match With Regex
How to Restrict Past Dates in Html5 Input Type Date
How to Render a Word Document (.Doc, .Docx) in the Browser Using JavaScript
How to Close Toggle Menu When Clicking Navigation Item Anchor Link
Hide Menu Sidebar When Clicking Outside the Bar or the Button
Dynamically Increase and Decrease an Input Text Box Size Depending on Another Selector Width