pstenstrm pstenstrm - 10 months ago 59
Ruby Question

Regex remove multiple whitespace and line-break inside HTML tag

Some background: we're adding a styleguide to our Middleman project. It's for other developers to use, so we want our code examples to be readable. We don't however want to have to update code in multiple places when we change a component.

We use redcarpet for markdown parsing and creating code examples.

<%= partial '../partials/component' %>

<%= partial '../partials/component' %>

This does however leave very messy and unreadable code examples. We can clean them up pretty well with htmlbeautifier. But we still have the issue with multiple whitespaces and linebreaks inside HTML tags.

It often looks like this:

<article class="default-s-sans teaser-media"




We want to remove the extra white space and line breaks inside the tag, that is between
. But not between elements, so it should leave this unchanged:

<span class="price">$100</span>
Word word

I have gotten this far:

html.gsub(/(?<=<)(\s{2,})(?>)/, ' ')

But it will only match whitespaces between
if there's nothing else between.

How can I match whitespaces between
but allow other characters as well?

Answer Source

You can use the matchdata object in gsub blocks:

html.gsub(/(?<=<)(.+)(?>)/m) { |match| match.gsub(/\n/, ' ').gsub(/\s+/, ' ') }