ruby on rails, replace last character if it is a * sign

22,321

Solution 1

Use the $ anchor to only match the end of line:

"sample*".gsub(/\*$/, '')

If there's the possibility of there being more than one * on the end of the string (and you want to replace them all) use:

"sample**".gsub(/\*+$/, '')

Solution 2

You can also use chomp (see it on API Dock), which removes the trailing record separator character(s) by default, but can also take an argument, and then it will remove the end of the string only if it matches the specified character(s).

"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"
"hello*".chomp("*")      #=> "hello"

Solution 3

String has an end_with? method

stringvariable.chop! if stringvariable.end_with? '*'

Solution 4

You can do the following which will remove the offending character, if present. Otherwise it will do nothing:

your_string.sub(/\*$/, '')

If you want to remove more than one occurrence of the character, you can do:

your_string.sub(/\*+$/, '')

Of course, if you want to modify the string in-place, use sub! instead of sub

Cheers, Aaron

Solution 5

You can either use a regex or just splice the string:

if string_variable[-1] == '*'
  new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end

That only works in Ruby 1.9.x...

Otherwise you'll need to use a regex:

if string_variable =~ /\*$/
  new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end

But you don't even need the if:

new_string = string_variable.gsub(/\*$/, '')
Share:
22,321

Related videos on Youtube

Kim
Author by

Kim

Updated on July 25, 2020

Comments

  • Kim
    Kim almost 4 years

    I have a string and I need to check whether the last character of that string is *, and if it is, I need to remove it.

    if stringvariable.include? "*"
     newstring = stringvariable.gsub(/[*]/, '')
    end
    

    The above does not search if the '*' symbol is the LAST character of the string.

    How do i check if the last character is '*'?

    Thanks for any suggestion

  • harsh4u
    harsh4u almost 11 years
    Thanks, help me so lots
  • vishB
    vishB almost 10 years
    really it helped more than any other replies
  • Christian.D
    Christian.D about 7 years
    It has to be noted, that with the answer above you need to operate on the returned value. For in-place replacement use .gsub!
  • Vishal
    Vishal almost 6 years
    Excellent answer, but what if we want to check both '*' and ',' and if found replace it with ' ' white space ?
  • pjumble
    pjumble almost 6 years
    @Vishal do you mean like this? "sample*,".gsub(/[\*,]+$/, ' ')