Skip to content

Instantly share code, notes, and snippets.

@mitchbudreski
Created September 20, 2021 16:08
Show Gist options
  • Save mitchbudreski/cf86379e33f8ffe3072f79e617e2754a to your computer and use it in GitHub Desktop.
Save mitchbudreski/cf86379e33f8ffe3072f79e617e2754a to your computer and use it in GitHub Desktop.
Keyify - Turning any string to make a dynamic object key
export function keyIfy(text) {
return text
.toString()
.toLowerCase()
.replace(/\s+/g, '_') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '_') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
//example
const KeyName = 'Mitch Likes Turtles'
const ObjectThing = {
dude: 'bro',
[keyIfy(KeyName)]: 'So does Zombie Jonathan'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment