繁体   English   中英

如何将字符串中每个单词的首字母大写

[英]How to capitalize first letter of each word in the string

如何在Ruby on Rails中的字符串中大写每个世界的首字母:

"goyette-xyz-is wide road".titleize returns "Goyette Xyz Is Wide Road".

我想要这样的输出:

"goyette-xyz is wide road".SOME-FUNCTION should return "Goyette-xyz-is Wide Road".

titleize删除了下划线和连字符,但我想将其保留在字符串中。

您可以像这样使用.titleize "i want to make the first letter of each work into a cap".titleize

你可以了解更多有关titleize从apidocks

标题(单词)公共

大写所有单词并替换字符串中的某些字符以创建外观更好的标题。 titleize用于创建漂亮的输出。 它不在Rails内部使用。

titleize也被别名为titlecase。

例子:

"man from the boondocks".titleize   # => "Man From The Boondocks"
"x-men: the last stand".titleize    # => "X Men: The Last Stand"
"TheManWithoutAPast".titleize       # => "The Man Without A Past"
"raiders_of_the_lost_ark".titleize  # => "Raiders Of The Lost Ark"

这种现实如何运作

# File activesupport/lib/active_support/inflector/methods.rb, line 115
def titleize(word)
  humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end

要实际上在作品中保留“-”,我们可以像这样在字符串类中添加一个新方法。

# ./lib/core_ext/string.rb
class String
  #"goyette-xyz-is wide road".titleize_with_dashes#=> "Goyette-xyz-is Wide Road"
  def titleize_with_dashes
    humanize.gsub(/\b('?[a-z])/) { $1.capitalize }
  end
end

您可以自己实现适当的方法:

class String
  def my_titleize
    split.map(&:capitalize).join(' ')
  end
end

"goyette-xyz-is wide road".my_titleize
#=> "Goyette-xyz-is Wide Road"

如果现在像我这样,即使是破折号也需要大写第一个字母,您可以这样做:

def titleize_and_keep_dashes(text)
  text.split.map(&:capitalize).join(' ').split('-').map(&:titleize).join('-')
end
titleize_and_keep_dashes("goyette-xyz-is wide road")
# => "Goyette-Xyz Is Wide Road".

.capitalize方法添加到您的String中,以自动将首字母大写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM