Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 218177
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T18:43:34+00:00 2026-05-11T18:43:34+00:00

I need to write a little ruby function that does word wrapping. I have

  • 0

I need to write a little ruby function that does word wrapping. I have got the following function :

def word_wrap(text, line_width)
  if line_width.nil? || line_width < 2
    line_width = 40
  end
  text.split("\n").collect do |line|
   line.length > line_width ? line.gsub(/.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
  end * "\n"
end

This is basically the word_wrap function included in Rails.

I would like to write a similiar function which parse a string with span elements inside, except that the tags should not be counted to wrap the line.

Example:

s = "Lorem <span>ipsum dolor</span> si<span>t</span> amet, conse<span>ctetur adipiscing elit</span> Praesent"

At the moment, word_wrap(s, 20) gives something like this:

Lorem <span>ipsum
dolor</span>
si<span>t</span>
amet,
conse<span>ctetur
adipiscing
elit</span> Praesent

It should be:

Lorem <span>ipsum dolor</span> si
<span>t</span> amet, conse<span>ctetur 
adipiscing elit</span> 
Praesent

As you can see, the new word_wrap function create lines of (max) 20 characters, without counting the <span> and </span> tags.

How would you do that? All suggestions are welcome!

Thanks in advance for your help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T18:43:35+00:00Added an answer on May 11, 2026 at 6:43 pm

    Here’s a regex solution

    irb> SPAN_RE = /(?i:<\/?span[^>]*>)/
    #=> /(?i:<\/?span[^>]*>)/
    irb> ALL_SPANS_RE = /(?:#{SPAN_RE}*(?!#{SPAN_RE}))/
    #=> /(?:(?i-mx:<\/?span[^>]*>)*(?!(?i-mx:<\/?span[^>]*>)))/
    irb> def word_wrap(str,width)
             full_re = /((?:#{ALL_SPANS_RE}.){0,#{width-1}}#{ALL_SPANS_RE}\S(?:#{SPAN_RE}+|\b))\s*/
             str.gsub(/\s*\n/, ' ').gsub(full_re, "\\1\n")
         end
    #=> nil
    irb> text =<<TEXT
         Lorem <span>ipsum
         dolor</span>
         si<span>t</span>
         amet,
         conse<span>ctetur
         adipiscing
         elit</span> Praesent
         TEXT
    #=> "Lorem <span>ipsum\ndolor</span>\nsi<span>t</span>\namet,\nconse<span>ctetur\nadipiscing\nelit</span> Praesent\n"
    irb> puts word_wrap(text,20)
    Lorem <span>ipsum dolor</span> si<span>
    t</span> amet, conse<span>ctetur
    adipiscing elit</span>
    Praesent
    #=> nil
    irb> word_wrap(text,20)
    #=> "Lorem <span>ipsum dolor</span> si<span>\nt</span> amet, conse<span>ctetur\nadipiscing elit</span>\nPraesent\n"
    

    Basically we grab as many characters as we can
    up to the word width, ignoring spans (and making
    sure we don’t grab parts of spans), and making sure
    we end on a non-space character, followed by
    either a span, or a word break.

    I’ll break down how the regex works:

    SPAN_RE matches one span tag (either <span> or </span> or or …)

    (?i:    - Start of a non-capturing parenthesis (useful for grouping patterns)
              The i flag means the inner pattern is case-insensitive
      <     - a literal '<' character
      \/?   - 0 or 1 a forward slashes
      span  - the letters "span"
      [^>]* - 0 or more other characters that are not a '>' character
      >     - a literal '>' character
    )       - end of the non-capturing parenthesis
    

    ALL_SPAN_RE matches all the spans at a given position – guaranteeing that the next character
    matched is not the start of a span tag.

    (?:             - Start of a non-capturing parenthesis (useful for grouping patterns)
      #{SPAN_RE}*   - 0 or more spans
      (?!           - Start of a negative lookahead
        #{SPAN_RE}  - exactly 1 span
                      Since this is inside a negative lookahead, it means that the next 
                      character in the string is not allowed to start a span
      )             - end of the negative lookahead
    )               - end of the non-capturing parenthesis
    

    This means that we can match one character after the ALL_SPAN_RE and be sure that we’re not
    grabbing part of a span.

    The full_re then just greedily matches as many characters as it can,
    up to the desired width (ignoring spans), making sure that it ends on a
    non-space character that is either the end of a word or followed by a span.

    (                     - start of a capturing parenthesis
      (?:                 - start of a non-capturing parenthesis
        #{ALL_SPANS_RE}   - any and all spans
        .                 - one character (which can't be the start of a span)
      )                   - end of non-capturing parenthesis
      {0,#{width-1}}      - match preceding pattern up to width-1 times
                            so this matches width-1 characters (ignoring spans)
      #{ALL_SPANS_RE}     - any and all spans
      \S                  - a non-whitespace character
                            we don't want to insert a "\n" after whitespace
      (?:                 - a non-capturing parenthesis
        #{SPAN_RE}+       - 1 or more spans
        |                 - OR
        \b                - the end of a word
                            these alternatives makes sure we aren't breaking in the middle of a word
       )                  - end of non-capturing parentheis
     )                    - end of capturing parenthesis
     \s*                  - any whitespace
                            since we're wrapping, we can just toss this when we insert the newline
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 135k
  • Answers 135k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer EasyMock doesn't support this so you're stuck with fallback of… May 12, 2026 at 6:59 am
  • Editorial Team
    Editorial Team added an answer Description from MSDN on how to setup your debugging session.… May 12, 2026 at 6:59 am
  • Editorial Team
    Editorial Team added an answer You should be able to do it using SQLDependency classes,… May 12, 2026 at 6:59 am

Related Questions

I feel a little bit kind of confused — for about 24 hours I
I have a Rails app with some basic models. The website displays data retrieved
I am working on a website hosted on microsoft's office live service. It has
Some of my recent web projects that I worked on, use a flow engine

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.