'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);
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wyck |
