Home > Software engineering >  Javascript / Node JS - using regex to transform a string?
Javascript / Node JS - using regex to transform a string?

Time:11-27

In my nodeJs code I make a REST call to a 3rd party api and one of the values in the response is a string value e.g:

  "total": "-15"

Note that this value can either be a negative number, zero or a positive number, but as a string.

e.g:

   "total": "-5"
   "total": "0"
   "total": " 3"

How can I convert this value to be as follows? Based off the above example:

   5 under
   level par
   3 over

I am quite new to node/javascript - is regex the best option to do this?

CodePudding user response:

As Blunt Jackson said, regex will probably be slower. Here is a conversion function example:

const toText = (value) => {
  const parsed = parseInt(value)
  return parsed  > 0 ? `${parsed} over` : parsed  < 0 ? `${Math.abs(parsed)} under` : 'level par';
}

console.log(toText("-5"));
console.log(toText("0"));
console.log(toText(" 3"));

CodePudding user response:

I like this question because I like Code Golf :D

So my suggestion would be this one-liner:

const toText = v => v == 0 ? "level par" : v < 0 ? `${-v} under` : `${ v} over`;

console.log(toText("-5"));
console.log(toText("0"));
console.log(toText(" 3"));

Works with Numbers or Strings as parameter.

  • Related