Skip to content

Instantly share code, notes, and snippets.

@coryschires
Created June 3, 2010 20:12
Show Gist options
  • Save coryschires/424402 to your computer and use it in GitHub Desktop.
Save coryschires/424402 to your computer and use it in GitHub Desktop.
wordbreak helper method
# Helper method to add html soft hyphen entities to words whose character length exceeds a given integer.
# Note: This is an overkill substitute for the poorly supported CSS word-break property.
def wordbreak(string, max_length = 12)
max_length = max_length < 5 ? 4 : max_length # force min max_length of 4
words = string.scan(/(?:"[\w'\.\-]*"\.?)|(?:'[\w'\.\-]*'\.?)|(?:[\w'\.]+)/)
words.each do |word|
if word.length > max_length
index = word.include?("-") ? word.index('-')+1 : max_length-2
existing_word = word.strip
new_word = word.insert(index, "&shy;")
string.gsub!(existing_word, new_word)
end
end
string
end
# rspec test
it "should add html soft hyphen entities to words whose character length exceeds a given integer" do
text = "This is a string with some superduperextralong words including some-hyphened-words. Hyphens should 'act-like-spaces'. No need for additional word breaks. But watch for quoted-hyphenated words -- \"double-quoted-hyphens\" - they should be treated as one word."
wordbreak(text).should == "This is a string with some superduper&shy;extralong words including some-hyphened-words. Hyphens should 'act-&shy;like-spaces'. No need for additional word breaks. But watch for quoted-hyphenated words -- \"double-&shy;quoted-hyphens\" - they should be treated as one word."
end
@coryschires
Copy link
Author

Helper method to add html soft hyphen entities to words whose character length exceeds a given integer.
Note: This is an overkill substitute for the poorly supported CSS word-break property.

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