Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enhance slugify to handle Camel Case?

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.

like image 499
Matt Norris Avatar asked Nov 06 '25 06:11

Matt Norris


1 Answers

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.

like image 56
AlanFoster Avatar answered Nov 07 '25 21:11

AlanFoster