Home > Mobile >  how to convert num into words
how to convert num into words

Time:08-27

this code should return 'One', i need to convert numbers into words. I'm think the problem in type of 'expr'

<code lang="javascript">
function wordedMath(expr) {
  expr = expr.toLowerCase();
  for (let i = 0; i < expr.length; i  ) {
    if(expr.includes('one')) expr.replace(expr.indexOf('one'), '1')

    if(expr.includes('two')) expr.replace(expr.indexOf('two'), '2')

    if(expr.includes('zero')) expr.replace(expr.indexOf('zero'), '0')

    if(expr.includes('plus')) expr.replace(expr.indexOf('plus'), ' ')

    if(expr.includes('minus')) expr.replace(expr.indexOf('minus'), '-')
  }
  expr = eval(''  expr  '')
  if(expr === 1) expr = 'One';
  if(expr === 2) expr = 'Two';
  if(expr === 0) expr = 'Zero';
  return expr
};
console.log(wordedMath('zero Plus one'));
</code>

CodePudding user response:

The replace method is not modifying an instance it's called on but returning a new string. Thus, you need to modify your code in the next way: expr = expr.replace(.... Also, it's a bad code style to rewrite a function attribute, I would rather recommend to use a local variable. Another improvement would be to use a lookup map (i.e. Object) containing mapping of words to their numerical representation, it will allow to create consistent back'n'forth transformations.

CodePudding user response:

Well first of all the code is not scalable at all and this a big problem when you need to expand a little bit.

Please try this off:

const numWords = {
  zero: 0,
  one: 1,
  two: 2,
  plus: " ",
  minus: "-",
};

function wordedMath(expr) {
  const arrToConvert = expr.split(" ");
  let strToEval = "";
  arrToConvert.forEach((word) => {
    const cased = word.toLowerCase();
    strToEval  = numWords[cased];
  });
  const result = eval(strToEval);
  return result;
}
console.log(wordedMath("zero Plus one")); // the result is 1

CodePudding user response:

I think this should work only follow this tutorial

Convert numbers into words

CodePudding user response:

Why this piece of code does not work as expected has a lot to do with the error you should be getting. Which is Uncaught SyntaxError: Unexpected token . Such an error means that the compiler found part of code that's not according to syntax. Considering that the eval function runs a given string as a piece of JS code, your string expr has some unexpected tokens for JS. If you debug your code you should see that value of expr right behind eval is still "zero Plus one". That's primarily why your code is not working.

EDIT

P.S. Using eval is bad practice in JS. You should consider some other options for your software.

  • Related