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?
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.
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.
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ò" .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With