Last active
September 22, 2017 17:30
-
-
Save guihatano/554fd7c6b07f4ec4e30c582b228c0185 to your computer and use it in GitHub Desktop.
Ruby On Rails code used to divide a html text with <p> tags. It is just a piece of code, you can copy and paste in a helper.
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
# After some research on how to divide a text with html tags my final solution is here | |
# this should work with strings. | |
# If you found a better solution, please let me know. | |
def divided_text(text) | |
# we have the start index of </p>, so we need do +3 to get the end | |
middle_index = middle_paragraph_index(text)+3 | |
first_text = text[0..middle_index] | |
# and here we have the '>' so we need do +1 | |
second_text = text[middle_index+1..-1] | |
text_list = [first_text, second_text] | |
end | |
private | |
# thanks to https://stackoverflow.com/questions/3520208/get-index-of-string-scan-results-in-ruby | |
def middle_paragraph_index(text) | |
# count the paragraphs | |
paragraphs_count = text.scan(/(?=<p>)/).count | |
half_paragraphs = paragraphs_count/2 -1 | |
res = [] | |
text.scan(/<\/p>/) do |c| | |
res << [c, Regexp.last_match.offset(0).first] | |
end | |
# res[] will have all </p> with their index | |
# we just want the index of the middle. | |
res[half_paragraphs][1] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment