Reputation: 1458
So I found myself needing to remove <br />
tags from the beginning and end of strings in a project I'm working on. I made a quick little method that does what I need it to do but I'm not convinced it's the best way to go about doing this sort of thing. I suspect there's probably a handy regular expression I can use to do it in only a couple of lines. Here's 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 the "<br />"
could really be anything, and it'd probably be more useful to make a general use function that takes as an argument the string that needs to be stripped from the beginning and end.
I'm open to any suggestions on how to make this cleaner because this just seems like it can be improved.
Upvotes: 4
Views: 5218
Reputation: 18594
You can use chomp!
and slice!
methods. See:
http://ruby-doc.org/core-1.8.7/String.html
Upvotes: 2
Reputation: 107989
def remove_breaks(text)
text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end
%r{...}
is another way to specify a regular expression. The advantage of %r is that you can pick your own delimeter. Using {} for the delimiters means not having to escape the /'s.
Upvotes: 1
Reputation: 42411
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'
Upvotes: 3
Reputation: 18569
gsub can take a regular expression:
text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
Upvotes: 10