cube
cube

Reputation: 29

How to replace all capital letters with an empty space in a string

I want to replace capitals with spaces. An example string is "Hey MrsMccarthy". I want it to return " ey rs ccarthy".

I tried different ways shown here to adapt it to my problem, but it doesn't seem to work. I first looked at how to find the capitals, for which I used:

string.scan /\p{Upper}/ # => ["H", "M", "M"]

but I am not sure how to combine so that it returns:

"ey rs ccarthy"

Upvotes: 1

Views: 604

Answers (2)

spickermann
spickermann

Reputation: 107037

I would do it like this:

string = "Hey MrsMccarthy"
string.gsub(/\p{Upper}/, ' ')
#=> " ey  rs ccarthy"

Upvotes: 3

sawa
sawa

Reputation: 168209

You can do:

"Hey MrsMccarthy".tr("A-Z", " ")
# => " ey  rs ccarthy"

Upvotes: 4

Related Questions