Skip to content

Instantly share code, notes, and snippets.

@kosperera
Last active August 28, 2020 11:15
Show Gist options
  • Save kosperera/ea02741505673325fc079f069a740c8b to your computer and use it in GitHub Desktop.
Save kosperera/ea02741505673325fc079f069a740c8b to your computer and use it in GitHub Desktop.
Vanilla JS Kebab Case

kebabCase

You want to have a look at LoDash or Underscore or Slugify for more reliable version. This is just for fun, and probably might not suitable for any production use 🤓

So, I wanted to kebabCase a string literal without having to refer any of the aboves. After reading few js libraries mentioned above, this is what I ended up.

function kebabCase(value, separator = '_') {
  // Expression to trim trailings
  var defaultToWS = '[' + separator.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + ']';
  
  // Make a string
  value = (value || '') + '';
  return value
    // Slugify value
    .replace(/[^\w\s-]/g, separator).toLowerCase().trim()
    // Make a kebab
    .replace(/([A-Z])/g, separator + '$1').replace(/[-_\s]+/g, separator).toLowerCase()
    // Trim trailings
    .replace(new RegExp('^' + defaultToWS + '+|' + defaultToWS + '+$', 'g'), '');
}

Usage

Here's the obvious stuff, you pass a deacent string literal, and it returns what you expect.

kebabCase('@Param (String): You entered a (string) value.');  
// Returns: 'param_string_you_entered_a_string_value'

Then, comes the exceptional stuff, you thro in few not-so-obvious values, like undefined, NaN et al.

kebabCase(undefined);   // Returns: ''
kebabCase(NaN);         // Returns: ''
kebabCase(null);        // Returns: ''

Finally, you pass in a non-string values, like a Number.

kebabCase(20200829133939999); // Returns '20200829133939999'

Change the separator?

So I thought it's good to have an extra option to change the separator charactor. You know, just to make things really complicated, not because I really need it.

kebabCase('@Param (String): You entered a (string) value.', '-');
// 'param-string-you-entered-a-string-value'
kebabCase('@Param (String): You entered a (string) value.', '');
// 'paramstringyouenteredastringvalue'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment