JV10
JV10

Reputation: 891

jQuery replace space with non-breaking space between two specific words

I've created the following script that searches the page for any instances of "Two words" and replaces the space with a non-breaking space:

var search = $('body').html();
search = search.replace(/Two words/g, function($1) {
    return ('<span class="no-break">' + $1 + '</span>');
});


$('body').html(search);

$(document).ready(function() {
    $('.no-break').each(function() {
        var $this = $(this);
        $this.text($this.text().replace(/ /g, '\u00A0'));
    });
});​

http://jsfiddle.net/Ggkpb/

However, when I place it onto my website, it's causing other jQuery and javascripts not to work.

Is there a better solution to mine? Something that won't upset the other scripts on my site.

Upvotes: 1

Views: 2082

Answers (3)

nnnnnn
nnnnnn

Reputation: 150030

This line:

$('body').html(search);

recreates every element in the body, minus any event handlers that may or may not have already been bound. So if you're going to use that technique you need to be one-hundred percent sure that you do it before you create any event handlers (except for handlers bound directly to the body or the document, I suppose).

Unrelated to the problem, note that you can make your code somewhat shorter because you can call .html() and .text() once each, passing a callback function that takes the current value and returns the new value (you don't need an .each() loop):

$(document).ready(function(){
    $('body').html(function(i, oldHtml){
        return oldHtml.replace(/Two words/g, '<span class="no-break">Two words</span>');
    }); 
    $('.no-break').text(function(i,oldText) {
        return oldText.replace(/ /g, '\u00A0');
    });
});

Upvotes: 2

phnkha
phnkha

Reputation: 7872

I think it's better if you separate your text from your javascripts. You could mark every block of text in your page using a Class

<div class="text">abcxyz...Two words...</div>

and then call

$('.text').each(function(){
      var search = $(this).html();
      search = search.replace(/Two words/g, function($1) {
            return ('<span class="no-break">' + $1 + '</span>');
      });
      $(this).html(search);
});

Upvotes: 0

Larry Battle
Larry Battle

Reputation: 9178

Here's another way of writing it. Since you didn't post an error messages, then I'm sure if this fixes your problem.

$(function(){
    $('body').html(function(){
        return $(this).html().replace(/Two words/g, '<span class="no-break">Two words</span>');
    }); 
    $('.no-break').each(function () {
        $(this).text($(this).text().replace(/ /g, '\u00A0'));
    });
});

Upvotes: 1

Related Questions