Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip/replace spaces within a string

Tags:

regex

ruby

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(' ', '')
like image 771
Grzegorz Kazulak Avatar asked Jun 16 '09 12:06

Grzegorz Kazulak


People also ask

How do you replace all spaces in a string?

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.

How do you replace a space in a string in Python?

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 “”).

How do you trim an extra space in a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.


2 Answers

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/,'')
like image 77
tvanfosson Avatar answered Oct 13 '22 00:10

tvanfosson


>> "5 900 00".gsub(' ','')
=> "590000"

Is it really a string?

.gsub returns the value, if you want to change the variable try .gsub!(" ", "")

like image 37
Jonas Elfström Avatar answered Oct 13 '22 01:10

Jonas Elfström