I have a string, say
var Str = 'My name is 123 and my name is 234'
.
Now I split this as
var arrStr = Str.split(' ');
I iterate through the array and have different logic depending upon whether the word is a string or number. How do i check that? I tried typeof
which didn't work for me.
EDIT:
After Seeing multiple answers. Now, I am in despair, which is the most efficient way?
If you care only about the numbers, then instead of using split you can use a regular expression like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\d+/g)
If you care about all pieces, then you can use another expression to find all non-space characters like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\S+/g)
Then iterate them one by one, and check if a given string is a number or not using the famous isNumeric()
function posted by @CMS in this famous question .
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Thanks to @Pointy and if you want them as numbers, input.match(/\\d+/g).map(Number)
.
You need to attempt to convert your array values to an integer.
To iterate them you can use a for
loop:
for(i=0;i<arrStr.length;i++) {
var result = !isNaN(+arrStr[i]) ? 'number' : 'string';
console.log(result);
}
Here I'm using a unary +
to attempt to convert the value of each array value to a number. If this fails, the result will be NaN
. I'm then using JavaScript's isNaN()
method to test if this value is NaN
. If it isn't, then it's a number, otherwise it's a string.
The result of this using the string you've provided is:
string
string
string
number
string
string
string
string
number
To use this in an if
statement, we can simply:
for(i=0;i<arrStr.length;i++) {
if(isNaN(+arrStr[i])) {
/* Process as a string... */
}
else {
/* Process as a number... */
}
}
To expound on Sniffer's answer...
var input = "My name is 123 and my name is 234";
var numberArray = input.match(/\d+/g);
var wordArray = input.match(/[A-Za-z]+/g);
for (var number in numberArray)
{
//do something
}
for (var word in wordArray)
{
//do something
}
While researching, I found out about the Number()
object. This is generally used to work with manipulation of numbers. MDN has a good documentation .
I found out that Number()
returns NaN
(Not a Number) when not passed a number. Since no number returns NaN, It could be a good way to check whether the passed object is string or a number literal.
So my code would be:
if (Number(arrStr[i]) == NaN){
//string
} else {
//number
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.