I need to convert a string value to its primitive type in JavaScript. Other values that are not of type String should just be returned.
Example:
String '
34'should be converted to34String
'34px'should be kept as'34px'trueshould returntrue'true'should returntrue
Here is a working example (please look at console).
I would like to know:
- If there is any better way to write the same function, in term of performance.
- If I missed some type or any other issues.
function convert(value) {
var result = value;
if (typeof value === 'string') {
// check if it is a empty character
value.trim();
if (value.length > 0) {
if (/\S/.test(value)) {
if (value === 'true') {
result = true;
} else if (value === 'false') {
result = false
} else if (!isNaN(value)) {
result = new Number(value);
}
}
}
}
return result;
}