Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My regex is not very good, but does anyone have a method to converting a "titled-cased" string to a ""slugified string? For example:

MyComponentName would transform/manipulate to my-component-name

So I could do something like:

public static String slugify(String s){
   /* Do Stuff... split at capital letter? */
   return s;
}
share|improve this question
up vote 5 down vote accepted
public static String slugify(String s) {
    return String.join(s.split('(?=[A-Z])'),'-').toLowerCase();
}

How this works:

We break the string apart into capitalized words, join them back together with hyphens, convert them all to lowercase.

share|improve this answer
    
Make sure you're running a recent API version on your class; in my org using exec anonymous, it doesn't include a hyphen up front. Otherwise, you can also use removeStart to remove it (either before or after toLowerCase). – sfdcfox Jan 23 at 1:11

Try something like the following:

static final Pattern caseChangePattern = Pattern.compile('[A-Z]?[a-z]+');
public static String slugify(String input)
    Matcher caseChangeMatcher = caseChangePattern.matcher(input);
    List<String> slugs = new List<String>();
    while (caseMatcher.find())
        slugs.add(caseMatcher.group().toLowerCase());
    return String.join(slugs, '-');
}

You can see some of the outputs:

system.assertEquals('my-component-name', slugify('MyComponentName'));
system.assertEquals('my-component-name', slugify('myComponentName'));
system.assertEquals('my-component-name', slugify('My Component Name'));

The reason I made a leading capital optional is that you may want to slugify method names which start with a lower-case letter, for example.

share|improve this answer
1  
This works, but it's also the slowest possible method because of all the looping and so on that you're responsible for. I really did the answer from @bigassforce, as it demonstrated a really cool replaceAll syntax that I doubt many people know about. – sfdcfox Jan 22 at 22:24
2  
@sfdcfox I didn't even realize split accepts a regex. I think a diversity of approaches is good, and agree this is slower. Not sure why his answer was deleted... – Adrian Larson Jan 22 at 22:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.