Removing a pattern from the beginning and end of a line in ruby

So I needed to remove tags <br />from the beginning and end of lines in the project I'm working on. I made a small little method that does what I need, but I'm not sure if this is the best way to do such things. I suspect there might be a handy regex that I can use to do this in only a few lines. Here is what I got:

def remove_breaks(text)  
    if text != nil and text != ""
        text.strip!

        index = text.rindex("<br />")

        while index != nil and index == text.length - 6
            text = text[0, text.length - 6]

            text.strip!

            index = text.rindex("<br />")
        end

        text.strip!

        index = text.index("<br />")

        while index != nil and index == 0
            text = test[6, text.length]

            text.strip!

            index = text.index("<br />")
        end
    end

    return text
end

Now it "<br />"really can be anything, and it would probably be more useful to make a general use function that takes as an argument a string that should be removed from the beginning and the end.

I am open to any suggestions on how to make it cleaner, because it just seems that it can be improved.

+3
5

gsub :

text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
+7
class String
    def strip_this!(t)
        # Removes leading and trailing occurrences of t
        # from the string, plus surrounding whitespace.
        t = Regexp.escape(t)
        sub!(/^(\s* #{t} \s*)+  /x, '')
        sub!(/ (\s* #{t} \s*)+ $/x, '')
    end
end

# For example.
str = ' <br /> <br /><br />    foo bar <br />    <br />   '
str.strip_this!('<br />')
p str                     # => 'foo bar'
+3

You can use chomp!and methods slice!. See: http://ruby-doc.org/core-1.8.7/String.html

+2
source
def remove_breaks(text)
  text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end

%r{...}- Another way to specify a regular expression. The advantage of% r is that you can choose your own delimeter. Using {} for delimiters means that you cannot escape /. S /.

+1
source

use replacement method instead

str.replace("<br/>", "")
-2
source

Source: https://habr.com/ru/post/1743479/


All Articles