Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
Parsing a user-input value

I would like to allow a user to enter some input, and the program to parse that as a js type, if it can. For example, in what the user types into the text input is:

  • Hello -> "Hello" (string)
  • 2.13 -> 2.13 (number)
  • true -> true (bool)

Would the following accomplish this in a very basic fashion, ignoring nested objects and such?

function parseValueFromText(text) {
    try {
        return JSON.parse(text);
    } catch(e) {
        if (e instanceof SyntaxError) {
            return text;
        } else {
            throw e;
        }
    }
}
let a=parseValueFromText('hello'),
    b=parseValueFromText(123);
console.log(a, typeof a);
console.log(b, typeof b);

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your implementation is pretty close, but if JSON.parse results in a string then you likely want the original string, not the result of the parse.

Also, I think that any exception should result in the original string.

function parseValueFromText(text) {
  try {
    const result = JSON.parse(text);
    if (typeof result !== 'string') return result;
  } catch {}
  return text;
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda