How to Remove a Substring After a Certain Character in a String Using Ruby

How do I remove a substring after a certain character in a string using Ruby?


new_str = str.slice(0..(str.index('blah')))

alt text

Remove everything after some characters

This can be relatively easily accomplished by running split("More info") on your strings. What that does is breaks the string in to an array like so:

new_string  = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]

What split does is it breaks a string apart in to an array, where each element is what preceded the argument. So if you have "1,2,3" then split(",") will return [1, 2, 3]

So to continue your solution, you can get the posting date like this:

new_string[0].strip

.strip removes spaces at the front or back of a string, so you'll be left with just "Posted today"

How to remove a certain character after substring in Ruby

If you don't want to use regex that sometimes difficult to understand use this:

def exclamation(sentence)
words = sentence.split
words_wo_exclams = words.map do |word|
word.split('').reverse.drop_while { |c| c == '!' }.reverse.join
end
words_wo_exclams.join(' ')
end

Remove substring from the string

You can use the slice method:

a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"

there is a non '!' version as well. More info can be seen in the documentation about other versions as well:
http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21

Remove @ sign and everything after it in Ruby

To catch anything before the @ sign:

my_string = "user@example.com"
substring = my_string[/[^@]+/]
# => "user"

How to delete specific characters from a string in Ruby?

Do as below using String#tr :

 "((String1))".tr('()', '')
# => "String1"

How do I remove all characters in a string until a substring is matched, in Ruby?

or with the regex:

str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"

you can read about lookaround at here



Related Topics



Leave a reply



Submit