Format HTML with indentation for improved readability and debugging.
Code
Utilitiesresult = []
level = 0
void_tags = %w[area base br col embed hr img input link meta param source track wbr]
html.scan(/<[^>]+>|[^<]+/).each do |token|
text = token.strip
next if text.empty?
if text.start_with?('</')
level -= 1
result << (' ' * (level * indent)) + text
elsif text.start_with?('<')
result << (' ' * (level * indent)) + text
tag = text.match(/<(\w+)/)[1].downcase
level += 1 unless void_tags.include?(tag) || text.end_with?('/>')
else
result << (' ' * (level * indent)) + text
end
end
return result.join("\n")Parameters
HTML string to format.
Number of spaces for indentation.
Server
More Ruby Snippets
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.
Array Tail
Get the last n elements of an array.
Array Union
Combine two arrays and remove duplicates to produce a union.