DEV Community

Shivashankar
Shivashankar

Posted on

1

Gem to truncate HTML strings efficiently ...

Generally we use truncate view helper to truncate the text.

But it has an issue that it truncate the html tag as well and in worst case, a partial html tag gets truncated.

For example:

truncate("The Rails philosophy includes two major guiding principles: <strong>Don't Repeat Yourself:</strong>", length: 7
0)

It gives output as

"The Rails philosophy includes two major guiding principles: &lt;strong..."

It is not the desired output we want. Reason is it breaks the html tags.

truncato gem comes as a rescue for handling this one. This Gem performs well while comparing to other Gems in truncating the html content, which is additional advantage of using this one.

This is how truncato gives output

Truncato.truncate("The Rails philosophy includes two major guiding principles: <strong>Don't Repeat Yourself:</strong>", max_len
gth: 70)
"The Rails philosophy includes two major guiding principles: <strong>Do...</strong>"

The HTML tag is smartly retained here even though it truncate the text with in it.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay