Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/b251d4492ec1d499c18aae6f42d73c71 to your computer and use it in GitHub Desktop.
Save awesome/b251d4492ec1d499c18aae6f42d73c71 to your computer and use it in GitHub Desktop.
Ruby sanitize string: remove nonword-chars, but preserve dashes and underscores.
str1 = "11423!@#$!@_asdf+_1234__asfsdf"
str1.gsub(/\W/,'')
# => "11423_asdf_1234__asfsdf" (seems legit…)
str2 = "11423!@#$!@_asdf+_1234__asf-sdf"
str2.gsub(/\W/,'')
# => "11423_asdf_1234__asfsdf" (doesn't preserve dash)
str2.gsub(/[^-\w]/,'')
# => "11423_asdf_1234__asf-sdf" (profit!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment