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'), '');
}
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'
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'