braindeaf

braindeaf

String.replace with anonymous function with multiple matches

I wonder if I can ask a newbie question, maybe..I’m trying to replace

<source>SOMETHING</source>

with

<code><pre>SOMETHING</pre></code>

So I can replace the entire match

iex(14)> String.replace("<source>(aaaM)</source>", ~r/<source>(.*)<\/source>/, fn match-> "<code><pre>#{match}</pre></code>" end)

**"<code><pre><source>(aaaM)</source></pre></code>"** 

But I need access to the first matched element, so (aaaM). Partly because I also want to HTML Escape it as well. Ok, I need to use the match in anonymous function…but..sadly.

iex(15)> String.replace("<source>(aaaM)</source>", ~r/<source>(.*)<\/source>/, fn match, code-> "<code><pre>#{match}</pre></code>" end) 
warning: variable "code" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:15

** (FunctionClauseError) no function clause matching in String.replace/4    
    
    The following arguments were given to String.replace/4:
    
        # 1
        "<source>(aaaM)</source>"
    
        # 2
        ~r/<source>(.*)<\/source>/
    
        # 3
        #Function<43.65746770/2 in :erl_eval.expr/5>
    
        # 4
        []
    
    Attempted function clauses (showing 1 out of 1):
    
        def replace(subject, pattern, replacement, options) when is_binary(subject) and is_binary(replacement) or is_function(replacement, 1) and is_list(options)
    
    (elixir 1.13.1) lib/string.ex:1477: String.replace/4

I’m not sure I follow, I’m now supplying 4 arguments. Even if I parenthesises the multiple arguments for the anonymous function. Anyone point out where I am being a dummy?

Many thanks

RobL

Most Liked

LostKobrakai

LostKobrakai

There is the function raw/1, but that also just wraps data into a {:safe, …} tuple. There’s no :raw tagged tuple support afaik.

jazzyer

jazzyer

I’m not sure I fully understand what you want to do, but this example might give you a sense:

def replace_characters(string) do
    to_replace = ["&", "<", ">", "/", "'"]

    String.replace(string, to_replace, fn
      "&" -> "H"
      "<" -> "E"
      ">" -> "L"
      "/" -> "L"
      "'" -> "O"
    end)
  end
iex::1> Module.replace_characters("fdsfd &<>/' dsfds")                              
"fdsfd HELLO dsfds"

Anonimous function is arity 1, that’s why it complains.

TheMaikXX

TheMaikXX

Hello, just a note. The function Phoenix.HTML.html_escape does always return {:safe, content} according to the spec. Because if it finds code, that needs to be escaped, it escapes it.. That tuple is for phoenix rendering where you put this tuple into template, informing it that the given content is already escaped.
There is also {:raw, content} that tells phoenix that you insist on putting the content into final result as-is.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement