I'm using tags to do some Javascripting.

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


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" #}
  • 2
    If you want to handle "apples & *!@#@! carrots" then you need the slugify plugin – Marion Newlevant Jul 15 '14 at 15:31

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.

{{ tag.name|kebab }}
  • 1
    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".

  • This should be the accepted answer. – carlcs Dec 3 '15 at 7:41

one more example with array parameter in replace method:

{{ "apples and carrots"|replace({" ":"-"}) }}
{# outputs "apples-and-carrots" #}
New contributor
Faiyaz Alam is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

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.