Given a string "5 900 000"
I want to get rid of the spaces using gsub
with the following pattern:
gsub(/\s/, '')
but that doesn't seem to work. Nor does:
gsub(' ', '')
Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.
The easiest approach to remove all spaces from a string is to use the Python string replace() method. The replace() method replaces the occurrences of the substring passed as first argument (in this case the space ” “) with the second argument (in this case an empty character “”).
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
If you want to do the replacement in place, you need to use:
str.gsub!(/\s/,'')
Alternatively, gsub returns the string with the replacements
str2 = str.gsub(/\s/,'')
EDIT: Based on your answer, it looks like you have some unprintable characters embedded in the string, not spaces. Using /\D/ as the search string may be what you want. The following will match any non-digit character and replace it with the empty string.
str.gsub!(/\D/,'')
>> "5 900 00".gsub(' ','')
=> "590000"
Is it really a string?
.gsub returns the value, if you want to change the variable try .gsub!(" ", "")
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