Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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

I'm using tags to do some Javascripting.

Is there any way that I can tell Craft to remove whitespace from {{ }} if the has spaces (for example 'apples and carrots'), and add dashes ('apples-and-carrots') ?

share|improve this question
up vote 11 down vote accepted

There are multiple ways to solve this:


Twigs url_encode filter:

{{ "apples and carrots"|url_encode }}
{# outputs "apples%20and%20carrots" #}

Twigs replace filter:

{{ "apples and carrots"|replace(' ', '-') }}
{# outputs "apples-and-carrots" #}


Twig PCRE Filters - Plugin:

{{ "apples and carrots"|preg_replace('/ /', '-') }}
{# outputs "apples-and-carrots" #}

Low Regex - Plugin:

{{ "apples and carrots"|regex('/ /', '-') }}
{# outputs "apples-and-carrots" #}

Slugify - Plugin:

{{ "apples and carrots"|slugify }}
{# outputs "apples-and-carrots" #}
share|improve this answer
If you want to handle "apples & *!@#@! carrots" then you need the slugify plugin – Marion Newlevant Jul 15 '14 at 15:31
Great answer, Victor. – Brad Bell Jul 15 '14 at 19:40
This really helped me out, thank you! – woolm110 Apr 14 '15 at 15:49

Craft has a filter for "Kebab Case", which I think is what you need. It strips out punctuation and replaces spaces with dashes. Useful if you need to format a field as a HTML attribute.

{{|kebab }}
share|improve this answer
Perfect answer. Worth noting that kebab didn't exist at the time this question was originally asked. It was added on Jun 2, 2015, when Craft 2.4.2664 was released. – Lindsey D Dec 3 '15 at 6:08

I'm not sure if this feature is newer than this question but you can also say {{ tag.slug }} to get apples-and-carrots. All letters become lowercase as well so the result is more "scripting-friendly".

share|improve this answer
This should be the accepted answer. – carlcs Dec 3 '15 at 7:41

Your Answer


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.