Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active December 13, 2022 09:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujanfernaud/da51b50540981f2aa17b9d1fa6652ee6 to your computer and use it in GitHub Desktop.
Save lujanfernaud/da51b50540981f2aa17b9d1fa6652ee6 to your computer and use it in GitHub Desktop.
Ruby and Nokogiri: Removing trailing spaces

Ruby and Nokogiri: Removing trailing spaces

sample_input = "<div>Hi&nbsp; &nbsp; &nbsp;</div>"
parsed_input = Nokogiri::HTML.parse(sample_input).text #=> "Hi   "

parsed_input.gsub(/\p{Space}*\z/, "") #=> "Hi"

\p{Space} catches any whitespace character.

Source: https://stackoverflow.com/questions/22645916/unable-to-strip-a-stubborn-space-from-a-ruby-string-nokogiri-is-involved#comment34491990_22646219

Regexp Character Properties: https://ruby-doc.org/core-2.5.0/Regexp.html#class-Regexp-label-Character+Properties

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment