Search code examples
stringelixirgettext

Translate specific phases in a string in elixir


I have a list with words that needs to be translated in strings, but not the whole string should be translated, only the words that is in the list.

a example

list_with_words_that_needs_to_translate = ["here", "with one", "a string"]

the strings that should be partly translated;

"here is a string", 

"word with one and two",

"and something that doesn't need translate"

and the expected result would be:

"here is a string" -> ["here", "is", "a string"] 
"word with one and two" -> ["word", "with one", "and two"]

so I can send the pieces to a func that translate them, returns them and the and Enum.join to get the new translated string.

The words will be translated to multible langs with gettext so I can't use String.replace and since the word-strings in the list has spaces in them I can't split on space.

Any pieces of advice?


Solution

  • You may use reduce to apply some function to every found word. Here is the example with String.upcase/1:

    iex(17)> tr = fn s1 -> list_with_words |> Enum.reduce(s1, fn(x, acc) -> 
                    String.replace(acc, x, String.upcase(x)) end) 
                  end
    
    iex(18)> tr.("here is a string")
    "HERE is A STRING"
    iex(19)> tr.("word with one and two")
    "word WITH ONE and two"
    iex(20)> tr.("and something that doesn't need translate")
    "and something that doesn't need translate"