Hey, I'm writing my first Rails app, and I'm trying to replace the underscores form an incoming id name with spaces, like this:
before: test_string
after: test string
How can I do this? Sorry if this is a bit of a dumb question, I'm not very familiar with regular expressions...
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).
Python Regex Escape Underscore Therefore, you don't need to escape the underscore character—just use it in your regular expression unescaped.
str.gsub!(/_/, ' ')
gsub
stands for 'global substitution', and the exclamation means it'll change the string itself rather than just return the substituted string.
You can also do it without regexes using String#tr!
:
str.tr!('_', ' ')
On rails you can use the simplier .humanize
and ruby's .downcase
method but be careful as it also strips any final '_id' string (in most cases this is just what you need, even the capitalized first letter)
'text_string_id'.humanize.downcase => "text string"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With