- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to turn words into whole numbers JavaScript?
We have to write a function that takes in a string as one and only argument, and return its equivalent number.
For example −
one five seven eight -------> 1578 Two eight eight eight -------> 2888
This one is pretty straightforward; we iterate over the array of words splitted by whitespace and keep adding the appropriate number to the result.
The code for doing this will be −
Example
const wordToNum = (str) => { const legend = ['zero', 'one', 'two', 'three', 'four', 'five', 'six','seven', 'eight', 'nine']; return str.toLowerCase().split(" ").reduce((acc, val) => { const index = legend.indexOf(val); return (acc*10 + index); }, 0); }; console.log(wordToNum('one five six eight')); console.log(wordToNum('zero zero two zero eight')); console.log(wordToNum('eight six seven five'));
Output
The output in the console will be −
1568 208 8675
Advertisements