3

I am looking to quickly and efficently convert a string like Digital Marketing to a slug like digital-marketing. How would I achieve this in Apex. I could break the string into two parts but I am looking for something better.

1

1 Answer 1

4

You can do a toLowerCase and replaceAll. This will convert to lower case, then remove special characters, then replace white space with hyphens.

String value = 'Digital Marketing';
String slug = value.toLowerCase().trim().replaceAll('[^a-z0-9\\s]+', '').replaceAll('[\\s]+', '-');
2
  • @Ali Gajani just in case you are looking to replace only the first occurrence of the white space use replaceFirst instead of replaceall
    – Rao
    Jun 8, 2015 at 21:15
  • I would also add a .removeStart('-').removeEnd('-') just to be safe regarding special characters and numbers at the beginning and end of the string. If one inserted a smiley face (:)) at the end, for example, the slug would end with a hyphen. Aesthetically speaking the dangling hyphen can bother some people. Mar 1, 2021 at 14:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .