1

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/

3
  • You missed to add jQuery lib see it works without replacing tags jsfiddle.net/praveen_jegan/E8ZPY/3 Commented Dec 12, 2013 at 5:50
  • it just working fine, what is th problem Commented Dec 12, 2013 at 5:52
  • FYI, you list input twice. Commented Dec 12, 2013 at 7:01

3 Answers 3

3
$('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.)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

1 Comment

Looks like it's replacing {REPLACE_ME} not in tags with <b>{REPLACED}</b> to me...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.