4

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.

Matt Norris
  • 8,596
  • 14
  • 59
  • 90

4 Answers4

4

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.

Matt Norris
  • 8,596
  • 14
  • 59
  • 90
AlanFoster
  • 8,156
  • 5
  • 35
  • 52
0

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);
});
Akbarali
  • 688
  • 7
  • 16
0

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);
sathishkumar
  • 1,780
  • 4
  • 20
  • 31
0

Try using:

str=str.toLowerCase() before or after the slugification.
Terry
  • 1,437
  • 2
  • 12
  • 26