Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!