Skip to content

Instantly share code, notes, and snippets.

@kawasako
Last active July 10, 2016 06:15
Show Gist options
  • Save kawasako/a0dfe672cca819b2ec30e56e6308bf63 to your computer and use it in GitHub Desktop.
Save kawasako/a0dfe672cca819b2ec30e56e6308bf63 to your computer and use it in GitHub Desktop.
const stringsRegExp = /("[^"]*?"|'[^']*?')/gm;
const numbersRegExp = /\d/gm;
const keysRegExp = /([{,])[\w\d]*?(\:)/gm;
const validTestRegExp = /^[\{\}\[\]\,]*$/;
const removeWhiteSpaces = function(str) {
return (str + '').replace(/\s*/gm, '');
};
const trim = function(str) {
return (str + '').replace(/^\s*(\S*?)\s*$/m, '$1');
};
export default function string2Object(input) {
if (!input) {
return input;
}
let memo = removeWhiteSpaces(input + '')
.replace(stringsRegExp, '')
.replace(numbersRegExp, '')
.replace(keysRegExp, '$1');
let isValid = validTestRegExp.test(memo);
if (isValid) {
return (new Function(`return ${trim(input)}`))();
}
return input;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment