Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active April 7, 2017 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/dccf82a4ed0b629d25a99ef7f8515e93 to your computer and use it in GitHub Desktop.
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.
/**
* 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