2

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.

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]+', '-');
  • @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 '15 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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