How to Remove Special Characters from a String in Ruby?
In this article, we will discuss how to remove special characters from a string in Ruby. In Ruby, special characters can be removed from a string using various methods. Special characters typically include punctuation marks, symbols, and non-alphanumeric characters. Let us explore different methods to remove special characters from a string in Ruby.
Table of Content
- Using Regular Expressions
- Using String#tr Method
- Using String#delete Method
Using Regular Expressions
The gsub
method with a regular expression pattern can be used to replace all characters that are not word characters with an empty string.
Syntax:
string.gsub(/[^\w\s]/, ”)
In the below example, we use the gsub
method with a regular expression pattern [^\w\s]
to replace all characters that are not word characters (\w
, alphanumeric characters and underscores) or whitespace characters (\s
) with an empty string.
# Removing special characters from a string using Regular Expressions
# Function to remove special characters using regular expressions
def remove_special_characters_regex(str)
str.gsub(/[^\w\s]/, '')
end
# Example usage:
example_string = "GeekforBeginner?"
puts "Original string: #{example_string}"
puts "After removing special characters: #{remove_special_characters_regex(example_string)}"
Output
Original string: GeekforBeginner? After removing special characters: GeekforBeginner
Using String#tr Method
The tr
method is used to delete special characters from a string.
Syntax:
str.tr(‘^a-zA-Z0-9 ‘)
In the below example, we use the tr
method with a complemented set ^A-Za-z0-9
to delete all characters that are not alphanumeric (letters or digits) from the string.
# Removing special characters from a
# string using String#tr method
# Function to remove special characters
#using String#tr method
def remove_special_characters_tr(str)
str.tr('^A-Za-z0-9', ' ')
end
# Example usage
example_string = "GeekforBeginner?"
puts "Original string: #{example_string}"
puts "After removing special characters: #{remove_special_characters_tr(example_string)}"
Output
Original string: GeekforBeginner? After removing special characters: GeekforBeginner
Using String#delete Method
The delete
method is used to remove special characters from a string.
Syntax:
string.delete(‘^a-zA-Z0-9 ‘)
In the below example,We use the delete method with a complemented set ^a-zA-Z0-9 to remove all characters that are not letters, digits, or spaces from the string.
# Removing special characters from a string
# using String#delete method
# Function to remove special characters using
# String#delete method
def remove_special_characters_delete(str)
str.delete('^a-zA-Z0-9 ')
end
# Example usage:
example_string = "GeekforBeginner?"
puts "Original string: #{example_string}"
puts "After removing special characters: #{remove_special_characters_delete(example_string)}"
Output
Original string: GeekforBeginner? After removing special characters: GeekforBeginner
Contact Us