Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a string in elixir?

Tags:

elixir

I'm working with slugs for elixir, the idea is: I have a string with [a-zA-Z0-9] words separated by hyphens. Like:

string = "another-long-string-to-be-truncated-and-much-text-here"

I want to be ensure that max string length equals to 30, but I also want to be sure that words aren't cut by half on reaching maximum length. So that first 30 symbols of string are another-long-string-to-be-trun but I want to have another-long-string-to-be with word truncated to be removed completely. How can I do that?

like image 581
asiniy Avatar asked Sep 08 '16 15:09

asiniy


People also ask

How do you remove elixir from string?

You can use String. slice/2 to remove the first N graphemes of a string, and binary_part/3 or pattern matching to remove the first N bytes of a string.

How do you truncate a string in Java?

Using String's split() Method. Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces. The first element of results will either be our truncated String, or the original String if length was longer than text.

Is Elixir a string?

Strings in Elixir are UTF-8 encoded binaries. Strings in Elixir are a sequence of Unicode characters, typically written between double quoted strings, such as "hello" and "héllò" .


1 Answers

UPD 12/2018 Yuri Golobokov posted the better solution here, I’d suggest to use it instead of the below.


The simplest approach would be:

"another-long-string-to-be-truncated-and-much-text-here"
|> String.slice(0..29) 
|> String.replace(~r{-[^-]*$}, "")
#⇒ "another-long-string-to-be"

There is one glitch with it: if the hyphen is exactly on position 31, the last term will be removed. To avoid this, one might explicitly check fot the condition above:

str = "another-long-string-to-be-truncated-and-much-text-here"
case str |> String.at(30) do                                      
  "-" -> str |> String.slice(0..29)                                  
  _   -> str |> String.slice(0..29) |> String.replace(~r{-[^-]*$}, "")
end                                                               
#⇒ "another-long-string-to-be"

or:

orig = "another-long-string-to-be-cool-cated-and-much-text-here"
str = orig |> String.slice(0..29) 
unless String.at(orig, 30) == "-", do: str = str |> String.replace(~r{-[^-]*$}, "")
str
#⇒ "another-long-string-to-be-cool"
like image 118
Aleksei Matiushkin Avatar answered Oct 19 '22 07:10

Aleksei Matiushkin