broccoli broccoli - 5 days ago 6
Javascript Question

Differentiate numbers and words in input using Regex

I'm trying to create a simple program that will allow the user to input numbers or words and have them sorted alphabetically (in case of words) or numerically (in case of numbers). For this I need an input that will differentiate between numbers and words so that for example 10, -10, 0.5 and -0.5 will be evaluated as numbers and everything else will be considered words.

So far I have come up with this:

function recordUserInput() {
userInput = $('input').val();

if (userInput.charAt(0).match(/^(-)?[0-9]/)) {
console.log('number', userInput);
}
else {
console.log('text', userInput);
}

}


However, negative numbers are still evaluated as text.

What am I doing wrong?

Answer

Use the unary +. If it returns NaN, it's not a number.

var type = isNaN(+userInput) ? 'text' : 'number';

parseFloat is probably not optimal. It parses left to right looking for a number and stops on a non-number. What it gathers, it turns to a number. parseFloat('123a') === 123.

Comments