How to strip white spaces from a string containing HTML content - ruby-on-rails

I could easily strip white space in the left side of a normal string like this:
" Remove whitespace".lstrip #=> "Remove whitespace"
But if the string contains HTML I am not able to do it:
#html_str = "<p> Remove whitespace </p>"
#html_safe_str = #html_str.html_safe #=> " Remove whitespace"
#html_safe_str.lstrip #=> "<p> Remove whitespace</p>"
#html_str.html_safe.lstrip is not working.
I dont want to remove all the s in the string. I want to remove all the s immediately after the opening <p> tag
Expected result: "Remove whitespace "
How is it possible?

In Rails 4, strip_tags has been combined with gsub. You can use gsub to remove s. Then, you need to use sanitizer method provided by ActionView:
#html_str = "<p> Remove whitespace </p>"
str = #html_str.gsub(/<p>\s*( \s*)+/, "<p>")
ActionView::Base.full_sanitizer.sanitize(str).lstrip # => "Remove whitespace "
It will work for Rails 3 as well as Rails 4.

You can do like this:
#html_str = "<p> Remove whitespace</p>"
#html_str = #html_str.gsub(" ", "") => "<p> Remove whitespace</p>"
#html_str1 = ActionController::Base.helpers.strip_tags(#html_str) => " Remove whitespace" #if you are doing this at controller level
#html_str1 = strip_tags(#html_str) => " Remove whitespace" #if you are doing this at view level
#now at the last
#html_str2 = #html_str1.strip => "Remove whitespace"
Shortly:
#html_str = "<p> Remove whitespace</p>"
#html_str1 = ActionController::Base.helpers.strip_tags(#html_str.gsub(" ", "")).strip => "Remove whitespace"
Hope this will work for you

If html_safe converts 's to white spaces, you can try:
#html_str.html_safe.lstrip
Hope that helps!

You can use gsub for that
#html_str = "<p> Remove whitespace</p>"
#html_str = #html_str.gsub(" ", "")
#html_safe_str = #html_str.html_safe
or
If you completely want to remove tags then as Andrey suggested, you can use strip_tags, but to use it in controller you need to call using ActionController::Base
#html_str = ActionController::Base.helpers.strip_tags("<p> Remove whitespace</p>").gsub(" ", "").lstrip
It will output : Remove whitespace
Hope this helps!

You can do it like this:
ActionController::Base.helpers.strip_tags(#html_str.html_safe).gsub(" ","").lstrip
# => "Remove whitespace"

Related

Can't get rid of some characters when pushing string to array

I'm creating some kind of custom tags that I'll use later to filter some datas. However, when I add the tags inside an array, I get the following:
"[\"witcher 3\", \"badass\", \"epic\"]"
#tags = []
params[:tags].split(', ').map do |tag|
#tags.push(tag.strip)
end
# About 5 lines under
FileDetail.create!(path: path, creation_date: date, tags: #tags)
Why do these \ show up, and why don't .strip work?
Thank you in advance
You are setting an array of strings in #tag, and \" represents an escaped character, in this case " which is used by ruby to represent String objects.
Consider the following code (an try it on IRB):
foo = ["bar", "baz"]
#=> ["bar", "baz"]
foo.inspect
#=> "[\"bar\", \"baz\"]"
foo.each { |f| puts "tag: #{f}" }
# tag: bar
# tag: baz
As you can see, there is really no \ character to strip from the string, its just how ruby outputs a String representation. So your code doesn't need .strip method:
#tags = []
params[:tags].split(', ').map do |tag|
#tags.push(tag)
end
Not related to your question, but still relevant: split method will return an array, so there is no need to create one before and then push items to it; just assign the returned array to #tags.
For example:
params[:tags] = "witcher 3, badass, epic"
#=> "witcher 3, badass, epic"
#tags = params[:tags].split(', ')
#=> ["witcher 3", "badass", "epic"]
If you want, you can still use map and strip to remove leading and trailing spaces:
params[:tags] = "witcher 3, badass , epic "
#=> "witcher 3, badass , epic "
params[:tags].split(",").map(&:strip)
#=> ["witcher 3", "badass", "epic"]

Removing leading and trailing double quotes in string in rails

I want to trim the leading and trailing quotes of a string without any replacement.. I have tried with gsub.. but nothing helped.. I want to achieve something like., "hai" to hai
In Java, I ll use like the following.,
String a="\"hai";
String z=a.replace("\"", "");
System.out.println(z);
Output:
hai
How can I achieve this in rails? Kindly pls help..
In my irb
2.2.3 :008 > str = "\"hai"
=> "\"hai"
2.2.3 :009 > str.tr!('\"', '')
=> "hai"
Why am I not able to get output without double quotes?? Sorry ., If my question doesn't meet your standard..
You can also use .tr method.
str = "\"hai"
str = str.tr('\"', '')
##OR
str.tr!('\"', '')
## OUTPUT
"hai"
You can pass a regex instead, try this
str = "\"hai"
str = str.gsub(/\"/, '')
Hope that helps!
This removes the leading and trailing double quotes from the string only. You get a new string and keep the old one.
str = "\"ha\"i\""
# => "\"ha\"i\""
new_str = str.gsub(/^"+|"+$/, '')
# => "ha\"i"
str
# => "\"ha\"i\""
Or you change the original string.
str.gsub!(/^"+|"+$/, '')
# => "ha\"i"
str
# => "ha\"i"
That's a ruby convention. Method names with an exclamation mark/point modify the object itself.
This should work:
str = "\"hai"
str.tr('"', '')
Note that you only escape (\") double-quotes in a string that is defined using double-quotes ("\""), otherwise, you don't ('"').

string replacement in Ruby: greentexting support for imageboard

I'm trying to have greentext support for my Rails imageboard (though it should be mentioned that this is strictly a Ruby problem, not a Rails problem)
basically, what my code does is:
1. chop up a post, line by line
2. look at the first character of each line. if it's a ">", start the greentexting
3. at the end of the line, close the greentexting
4. piece the lines back together
My code looks like this:
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split('\n') #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
a << str2 #close the greentext tag
end
end
c1 = ""
arr_lines.each do |a|
strtmp = '\n'
if arr_lines.index(a) == (arr_lines.size - 1) #recombine the lines into text
strtmp = ""
end
c1 += a + strtmp
end
c2 = c1.gsub("\n", '<br/>').html_safe
end
But for some reason, it isn't working! I'm having weird things where greentexting only works on the first line, and if you have greentext on the first line, normal text doesn't work on the second line!
Side note, may be your problem, without getting too in depth...
Try joining your array back together with join()
c1 = arr_lines.join('\n')
I think the problem lies with the spliting the lines in array.
names = "Alice \n Bob \n Eve"
names_a = names.split('\n')
=> ["Alice \n Bob \n Eve"]
Note the the string was not splited when \n was encountered.
Now lets try this
names = "Alice \n Bob \n Eve"
names_a = names.split(/\n/)
=> ["Alice ", " Bob ", " Eve"]
or This "\n" in double quotes. (thanks to Eric's Comment)
names = "Alice \n Bob \n Eve"
names_a = names.split("\n")
=> ["Alice ", " Bob ", " Eve"]
This got split in array. now you can check and append the data you want
May be this is what you want.
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split(/\n/) #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
# Use a.insert id you want the existing ">" appended to it <p class = "unkfunc">>
# Or else just assign a[0] = str1
a << str2 #close the greentext tag
end
end
c1 = arr_lines.join('<br/>')
c2 = c1.html_safe
end
Hope this helps..!!
I'm suspecting that your problem is with your CSS (or maybe HTML), not the Ruby. Did the resulting HTML look correct to you?

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

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.
gsub can take a regular expression:
text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
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'
You can use chomp! and slice! methods. See:
http://ruby-doc.org/core-1.8.7/String.html
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.
use replace method instead
str.replace("<br/>", "")

Replace white space with AND in ruby

I have someone entering a form with some string input. What I need to do is replace any white space in the string with " AND " (no quotes). What's the best way to do this?
Also, how would I go about doing this if I wanted to remove all the whitespace in the string?
Thanks
to replace with and:
s = 'this has some whitespace'
s.gsub! /\s+/, ' AND '
=> "this AND has AND some AND whitespace"
to remove altogether:
s = 'this has some whitespace'
s.gsub! /\s+/, ''
=> "thishassomewhitespace"
Split and join is another technique:
s = " a b c "
s.split(' ').join(' AND ')
# => "a AND b AND c"
This has the advantage of ignoring leading and trailing whitespace that Peter's RE does not:
s = " a b c "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "
Removing whitespace
s.split(' ').join('')
# or
s.delete(' ') # only deletes space chars
use gsub method for replacing whitespace
s = "ajeet soni"
=> "ajeet soni"
s.gsub(" "," AND ")
=> "ajeet AND soni"

Resources