Michael Robinson
Michael Robinson

Reputation: 2137

Javascript Replace removes HTML

Javascript's string replace function seems to be stripping HTML tags, is there a way to disable this?

Example:

http://jsfiddle.net/TDd7w/

$('#pageEnumeration').text(function(){
    return $(this).text().replace(/^Showing \d+-\d+ of/, 'Showing ');
});
<p id="pageEnumeration">
  Showing 1-25 of 45 records found:
  <br>
  containing the terms:
  <span class="italic">cat</span>
</p>

Upvotes: 0

Views: 140

Answers (2)

Jason M. Batchelor
Jason M. Batchelor

Reputation: 2951

Actually, what it comes down to is the fact that you're accessing the text node through .text(), which does completely strip out markup.

http://jsfiddle.net/mori57/dkLLX/

Is this what you were looking for?

$('#pageEnumeration').html(function(i, htm){
    return htm.replace(/^Showing \d+-\d+ of/, 'Showing ');
});

You need to access using the .html() method, not .text() if you want to preserve element nodes.

Upvotes: 4

nhahtdh
nhahtdh

Reputation: 56819

You need to grab the specific text node, or process innerHTML directly. The stripping of tags is caused by text().

var $pageEnum = $('#pageEnumeration');

if ($pageEnum.length > 0) {
    $pageEnum[0].innerHTML = $pageEnum[0].innerHTML.replace(/^Showing \d+-\d+ of/, 'Showing ');
}

Demo

Upvotes: 0

Related Questions