简体   繁体   中英

how to convert num into words

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>

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 (ie Object) containing mapping of words to their numerical representation, it will allow to create consistent back'n'forth transformations.

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

I think this should work only follow this tutorial

Convert numbers into words

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM