用regex替换,然后撤消

replace with regex then undo

本文关键字:然后 撤消 替换 regex      更新时间:2023-09-26

我遇到了一个非常独特的问题,我试图运行一些jquery逻辑来临时替换页面上的文本。然后运行一些逻辑(我为我正在使用的工具截屏)。到目前为止,这很有效,问题是由于遗留代码,我需要恢复replace调用在页面上所做的更改。

有什么最好的方法吗?对于好奇的人,我目前有:

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

谢谢!

我会质疑你的动机和推理,但我会提供一个答案:

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

之后:

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

(除非您需要保留事件处理程序等,在这种情况下需要克隆)

克隆方法:

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

不是很严重,但我必须…

location.reload();

之前

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

之后

$('body').html(bodyHTML)