Reputation: 8836
I'd like to write a JavaScript function to slugify a string, with one more requirement: handle Camel Case. For example, thisIsCamelCase
would become this-is-camel-case
.
How do I modify a function like this to do so?
EDIT
Added full, answered example.
Upvotes: 4
Views: 2036
Reputation: 904
I wanted to generate a slug in snake keys. This method worked for me
$(document).on('keyup', '.slugGen', function () {
let slug = $(this).val().toLowerCase().replace(/ /g, '_').replace(/[^\w-]+/g, '');
$(this).closest('tr').find('#slug').val(slug);
});
Upvotes: 0
Reputation: 8306
You just need to add one line of code to what you posted
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; });
This brings the remaining code to be
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; }); // camel case handling
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;",
to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(from[i], to[i]);
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
Edit :: I also deleted the useless new RegExp logic too. Edit :: Added 'g' to find all caps, not just the first one.
Upvotes: 4
Reputation: 1816
This will help you!
var strings = 'toDo';
var i=0;
var ch='';
while (i < strings.length){
character = strings.charAt(i);
if (character == character.toUpperCase()) {
//alert ('upper case true' + character);
character = "-" + character.toLowerCase();
}
i++;
ch += character;
}
//to-do
alert(ch);
Upvotes: 0