2

I'm in need of a function that takes in a string and turns words that are equal to a number into an integer.'one five seven three' -> 1573

  • 1
    Can you show a list of example? Why don't you use a library that can humanize number ? Otherwise, a simple Map would do the trick. – Dimitri Kopriwa Mar 02 '19 at 22:12
  • 1
    Possible duplicate of [Javascript: Words to numbers](https://stackoverflow.com/questions/11980087/javascript-words-to-numbers) – Ayoub Benayache Mar 02 '19 at 22:29

4 Answers4

3

Here's one way to do it:

const numWords = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

const changeStrToNum = str => {
  let num = '';
  str.split` `.forEach(numWord => {
    num += numWords.indexOf(numWord);
  });
  return +num;
};

console.log(changeStrToNum('one five seven three'));
Scott Rudiger
  • 1,224
  • 12
  • 16
2

You could take an object with the digit names and their values and return a new number.

var words = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 },
    string = 'one five seven three',
    value = +string
        .split(' ')
        .map(w => words[w])
        .join('');        

console.log(value);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Upvoted yours because it's probably better to use O(1) lookup on an object literal rather than `indexOf` on an array in my answer. – Scott Rudiger Mar 02 '19 at 22:22
0

While it seems similar to with JavaScript numbers to Words you could invert this code for your use case

Posting gist with code for reference https://gist.github.com/RichardBronosky/7848621/ab5fa3df8280f718c2e5263a7eabe004790e7e20

Oleg Andreyev
  • 647
  • 5
  • 20
0

You can split first on space and than use reduce

let words  = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }
let string = 'one five seven three'
let value  = string
             .split(' ')
             .reduce((o, i) => o + words[i] ,'')      

console.log(value);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60