7

Using Twig, is it possible to strip out or replace a non-breaking space ( )?

I've got a string variable price (returned from the currency filter) that prints like this:

Nkr 100,00

What I'd like, is to strip the Nkr  part, so the string looks like this:

100,00

However, {{ price|replace('Nkr ', '') }} does nothing, as the replace filter doesn't appear to actually match the non-breaking space.

{{ price|replace({'Nkr' : ''}) }} strips out the Nkr part, but leaves the  ; and I'm unable to remove it.

Here's what I tried already (after stripping the Nkr part):

{{ price|replace({' ' : ''}) }}
{{ price|raw|replace({' ' : ''}) }}
{{ price|striptags }}
{{ price|raw|striptags }}
{{ price|trim }}
{{ price|raw|trim }}
{{ price|replace({ '\u00a0' : '' }) }}
{{- price -}} 
{% spaceless %}{{ price }}{% endspaceless %}
0

4 Answers 4

5

You just think it is   that get's returned from the filter, because that's how your developer tools display it, but in fact it is a UTF-8 encoded non-breaking space character. Have a look at the source code that is output and you won't see the  .

The filter gets the formatting pattern from the app/framework/i18n/data/no.php file. Everything in this file is UTF-8 encoded and the non-breaking space is no exception.

So how can we remove it? Copy-and-pasting doesn't always work, because it depends on the apps used. On Mac OS X 10.11 I was able to simply copy the string from the source code view in the Safari dev tools to Atom editor and it worked. I can also generate the character with Alt+Space. Copying the snippet into this answer doesn't work though, it somehow converts it to a normal space:

{{ price|replace('Nkr ') }}

Important sidenote:

Mac OS X users who are like me and sometimes accidentially enter a non-breaking space character into their source code and then go mad trying to fix the error, have a look at this Apple Stack Exchange post: What's alt+spacebar character and how to disable it?

Atom editor users can install the highlight-nbsp package.

0
6

Here's a different spin... Try removing everything that's not numeric or comma.

{{ price|replace('/[^0-9,]/', '') }}
1
  • Ah, that's clever – works like a charm in this specific instance, thanks! However I'd still like to know how to strip out the   in cases where a greedy regex like that wouldn't work (i.e. when I don't have a numeric string to deal with...) Feb 16, 2016 at 1:06
2

To add space between two words use below code:

{{ price|replace({" ": " "})|raw  |nl2br }}

This will work.

1

If you need to trim a non-breaking space which is the UTF-8 encoded non-breaking space character:

{{ value|trim(" \t\n\r\0\x0B\xC2\xA0") }}

This works because internally Twig uses the PHP trim, ltrim, and rtrim functions.

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.