Created
June 3, 2010 20:12
-
-
Save coryschires/424402 to your computer and use it in GitHub Desktop.
wordbreak helper method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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, "­") | |
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­extralong 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." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.