Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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);

Try using:

str=str.toLowerCase() before or after the slugification.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top