Javascript: Words to numbers

JavaAndCSharp picture JavaAndCSharp · Aug 16, 2012 · Viewed 14.9k times · Source

How can I convert words to numbers in JavaScript?

Example: "Nineteen days from now" would become "19 days from now".

I'm fine with using jQuery or another library - hopefully a smallish one if it's not jQuery.

Answer

JavaAndCSharp picture JavaAndCSharp · Aug 18, 2012

Here's my JavaScript replacement of @Greg Hewgill's Python module, minus the testing from the bottom of the code:

var Small = {
    'zero': 0,
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9,
    'ten': 10,
    'eleven': 11,
    'twelve': 12,
    'thirteen': 13,
    'fourteen': 14,
    'fifteen': 15,
    'sixteen': 16,
    'seventeen': 17,
    'eighteen': 18,
    'nineteen': 19,
    'twenty': 20,
    'thirty': 30,
    'forty': 40,
    'fifty': 50,
    'sixty': 60,
    'seventy': 70,
    'eighty': 80,
    'ninety': 90
};

var Magnitude = {
    'thousand':     1000,
    'million':      1000000,
    'billion':      1000000000,
    'trillion':     1000000000000,
    'quadrillion':  1000000000000000,
    'quintillion':  1000000000000000000,
    'sextillion':   1000000000000000000000,
    'septillion':   1000000000000000000000000,
    'octillion':    1000000000000000000000000000,
    'nonillion':    1000000000000000000000000000000,
    'decillion':    1000000000000000000000000000000000,
};

var a, n, g;

function text2num(s) {
    a = s.toString().split(/[\s-]+/);
    n = 0;
    g = 0;
    a.forEach(feach);
    return n + g;
}

function feach(w) {
    var x = Small[w];
    if (x != null) {
        g = g + x;
    }
    else if (w == "hundred") {
        g = g * 100;
    }
    else {
        x = Magnitude[w];
        if (x != null) {
            n = n + g * x
            g = 0;
        }
        else { 
            alert("Unknown number: "+w); 
        }
    }
}

I got hung up a bit on the RegEx-ing and the for-each bug in IE, but here it is. A fairly decent conversion from Python to JavaScript, if I can say so myself, which I can't. It needs some work - "One hundred and twenty" won't work - but it's good enough for now. Of course, thanks to @Greg Hewgill for the original, written in Python.