Valchris
Valchris

Reputation: 1481

replace with regex then undo

I have a rather unique problem where I'm trying to run some jquery logic to replace text temporarily on a page. Then run some logic (I take a screenshot for a tool I'm using). So far this works great, the problem is that due to legacy code I need to revert the changes the replace call did on the page.

Any ideas on the best way to do this? For the curious, I currently have:

$('body').html($('body').html().replace(/[a-zA-Z0-9\\*]*@.*\\.com/g,'[replaced for screenshot]'))

Thanks!

Upvotes: 0

Views: 278

Answers (3)

MDEV
MDEV

Reputation: 10838

I'd question your motives and reasoning, but I'll provided an answer nonetheless:

var backup_body_html = $('body').html();
$('body').html(backup_body_html.replace(/[a-zA-Z0-9\\*]*@.*\\.com/g,'[replaced for screenshot]'));

Afterwards:

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

(Unless you need to keep hold of event handlers etc, in which case cloning is needed)

Cloning method:

var body_children = $("body").clone(true,true).children();
//other stuff (i.e. replacements)
//then:
$("body").html("");
$("body").append(body_children);

Upvotes: 3

ryan
ryan

Reputation: 6655

Not completely serious but I have to...

location.reload();

Upvotes: 1

Roger Barreto
Roger Barreto

Reputation: 2284

Before

var bodyHTML = document.body.innerHTML;
$('body').html(bodyHTML.replace(/[a-zA-Z0-9\\*]*@.*\\.com/g,'[replaced for screenshot]'));

After

$('body').html(bodyHTML)

Upvotes: 0

Related Questions