Alvaro Castro
Alvaro Castro

Reputation: 841

JS - Best way to cast string value to number, boolean or string?

As the title says, I'm trying to build a function that given a string value as its input, it returns the value casted properly.

So far I got this, I think it looks ugly and have the feeling it can be solved in a better way.

Examples:

const smartCast = function (value) {
  if (value === 'true') {
    return true;
  }
  if (value === 'false') {
    return false;
  }
  if (!isNaN(value)) {
    return Number(value);
  }

  return value;
};

console.log(smartCast('ahoy!') === 'ahoy!');
console.log(smartCast('hello there') === 'hello there');
console.log(smartCast('412') === 412);
console.log(smartCast('71.3') === 71.3);
console.log(smartCast('true') === true);
console.log(smartCast('false') === false);

Let me know if there is a case I'm not taking into account.

Upvotes: 1

Views: 176

Answers (2)

Ebuall
Ebuall

Reputation: 1446

Take a look at empty string case and date https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Examples

Upvotes: 0

Alexandre Borela
Alexandre Borela

Reputation: 1626

function cast(value) {
  if (typeof value !== 'string')
    return value

  // Ignore values that would start an array or object.
  if (/^\s*[{\[]/.test(value))
    return value

  try {
    // Try to parse as some value.
    return JSON.parse(value)
  } catch(e) {
    // If there's an error, we will assume it is just
    // a string.
  }

  return value
}

console.log(typeof cast('false')) // boolean
console.log(typeof cast('true')) // boolean
console.log(typeof cast('1')) // number
console.log(typeof cast('3.14')) // number
console.log(typeof cast('abc')) // string
console.log(typeof cast('[1,2,3]')) // string
console.log(typeof cast('{"abc":1}')) // string

Upvotes: 2

Related Questions