John Baker
John Baker

Reputation: 435

Selectively replacing text with HTML with jQuery

How can I replace text on a page using jQuery without replacing tags and text within tags such as: <a>,<input>,<button>,<textarea>,<input>,<select>.

For example, here is the HTML code

<html>
<head>
    <title>Testing</title>
</head>
<body>
    Hello, this is a test replacing {REPLACE_ME} with <b>{REPLACED}</b>.
    <br/><br/>
    I want {REPLACE_ME} and {REPLACE_ME} to be <b>{REPLACED}</b>, however I don't want this <a href="#">{REPLACE_ME}</a> to become <a href="#">{REPLACED}</a>.
    Same with <textarea>{REPLACE_ME}</textarea>, it shouldn't change.
    <br/><br/>
</body>

I have this jQuery to replace the text

var replaced = $("body").html().replace(/{REPLACE_ME}/gi,'<b>{REPLACED}</b>');
 $("body").html(replaced);

Here it is on JSFiddle

http://jsfiddle.net/E8ZPY/

Upvotes: 1

Views: 270

Answers (3)

Paul Draper
Paul Draper

Reputation: 83323

$('body, body *:not(a,button,textarea,option)').contents().filter(function() {
    return this.nodeType === 3;
}).each(function() {
    var escaped = $('<div></div>').text($(this).text()).html();
    $(this).replaceWith(escaped.replace(/\{REPLACE_ME\}/gi,'<b>{REPLACED}</b>'));
});

JSFiddle

(I didn't need to include input, and I used option instead of select, since option is the one with text nodes for children.)

Upvotes: 3

kavun
kavun

Reputation: 3381

var replaced = $("body").html().replace(/[^>]{REPLACE_ME}[^<]*/gi, '<b>{REPLACED}</b>');
$("body").html(replaced);

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

first add jquery file

apply "\" in regex pattern for special character

var replaced = $("body").html().replace(/\{REPLACE_ME\}/gi,'<b>{REPLACED}</b>');
                             // see here^^^__________^^^^    

$("body").html(replaced);

see updated fiddle

Upvotes: 0

Related Questions