Last active
July 10, 2016 06:15
-
-
Save kawasako/a0dfe672cca819b2ec30e56e6308bf63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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