Last active
April 7, 2017 04:56
-
-
Save kevinweber/dccf82a4ed0b629d25a99ef7f8515e93 to your computer and use it in GitHub Desktop.
Convert a given string so it can be used as the unique key/id of a JavaScript object. If no string is provided, a random string is generated.
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
/** | |
* Converts a given string so it can be used as the key of a JavaScript object. | |
* If no string is provided, a random string is generated. | |
*/ | |
function generateObjectKey(string) { | |
var key; | |
if (typeof string === "undefined") { | |
string = Math.random().toString(36).substr(2, 5); | |
} | |
// Remove underscore and all non-alphanumeric characters | |
key = string.replace(/[_\W]+/g, ""); | |
return key; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment