javascriptjqueryhtmlcssregex

replacing spaces with  


Let's assume the following element (look for the trailing and leading spaces):

<p>
    <span class="item">Lorem Ipsum is simply dummy text </span><span class="item">of the printing and typesetting</span><span class="item"> industry.</span>
</p>

I want to replace all spaces with &nbsp;, due to display: inline-block weird behavior shown here: http://jsfiddle.net/SQuUZ/ (I don't know about all browsers, but latest Chrome and Firefox both act the same).

Now, since javascript is an option here, so is jQuery, I could:

$('p').text($('p').text().replace(/ /g, '&nbsp;'));

But it escapes the &nbsp; and turns out into a&nbsp;mess&nbsp;of&nbsp;entities.

Obviously, for such purposes we could use $('p').html():

$('p').html($('p').html().replace(/ /g, '&nbsp;'));

But this one is even worse, because, it also adds &nbsp; within the tags themselves:

<p>
    <span&nbsp;class="item">Lorem&nbsp;Ipsum&nbsp;is&nbsp;simply&nbsp;dummy&nbsp;text&nbsp;</span><span&nbsp;class="item">of&nbsp;the&nbsp;printing&nbsp;and&nbsp;typesetting</span><span&nbsp;class="item">&nbsp;industry.</span>
</p>

<!-- TL;DR -->
<span&nbsp;class="item"></span> <!-- is actually invalid... -->

And it breaks everything...

Notes:

What options do I have here?

Update:

In fact, could anyone explain why there is such a bug with that multi-line / single-line display: inline-block;? (See fiddle link above, and examine...)

Question migrated to display: inline-block; weird spacing behavior


Solution

  • $('p').contents().filter(function(){
        return this.nodeType == 3 // Text node
    }).each(function(){
        this.data = this.data.replace(/ /g, '\u00a0');
    });
    

    DEMO