//from the linked SO answer
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.trim().split(/\s*,\s*/).map(function(word) {
return isNumeric(word) ? Number(word) : word;
});
console.log(z);
How does this work?
isNumeric
It's important to note that you need a way of detecting what is and isn't a number. I suggest using the implementation shown here (the same one as my example) as it's robust and would not throw false positives or false negatives. A lot of the answers here will ignore some valid numbers (e.g., +3
or -3
) or parse something invalid as a number (e.g., ""
).
Let's assume you have a function called isNumeric()
that returns a boolean for whether an input is numeric or not. If need be, you might need to alter the implementation to suit your needs, e.g., if you only want to use whole number or only positive numbers.
Splitting into separate words
The string you have would need to be separated into separate chunks of words. This is done in the following fashion
var input = " The, 1, 2 , Fox , Jumped , 3, Over, 4 ";
input.trim() //make sure there are no beginning and ending spaces
.split(/\s*,\s*/); //split on a comma surrounded by any amount of spaces. That removes spaces from start/end of each of the words
//["The", "1", "2", "Fox", "Jumped", "3", "Over", "4"]
Using .map
The map() method can be ran on an array to transform it into a new array. This us done by transforming each element using a callback function. The callback given simply checks if a word is actually a number - if so, it parses it as a number using Number for explicit type conversion. Note that you should NOT have new Number(word)
as that creates a Number
object, not the numeric primitive type.
It might be useful to note that implicit conversion could be done using the +
operator. For example:
+"500" //500
+"hello" //NaN
To the in the beginning of my answer could use +word
instead of Number(word)
but just I find explicit conversion to be easier to understand.