diff --git a/lib/string_tools/core_ext/string.rb b/lib/string_tools/core_ext/string.rb index bbef1a9..6d03eb6 100644 --- a/lib/string_tools/core_ext/string.rb +++ b/lib/string_tools/core_ext/string.rb @@ -204,6 +204,30 @@ def mb_downcase mb_chars.downcase.to_s end + # Public: returns copy of string with all non-printable characters removed + # + # Examples + # + # "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable + # # => "qwerty" + # + # Returns String + def remove_nonprintable + gsub(/[^[:print:]]/i, '') + end + + # Public: removes all non-printable characters from string + # + # Examples + # + # "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable! + # # => "qwerty" + # + # Returns String + def remove_nonprintable! + replace(remove_nonprintable) + end + private def surround_with_ansi(ascii_seq) diff --git a/spec/string_spec.rb b/spec/string_spec.rb index 23d584d..11f9e26 100644 --- a/spec/string_spec.rb +++ b/spec/string_spec.rb @@ -6,4 +6,16 @@ describe '#mb_downcase' do it { expect("Кириллица".mb_downcase).to eq("кириллица") } end + + describe '#remove_nonprintable' do + let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" } + + it { expect(string.remove_nonprintable).to eq 'string with weird characters' } + end + + describe '#remove_nonprintable!' do + let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" } + + it { expect { string.remove_nonprintable! }.to change { string }.to('string with weird characters') } + end end