[英]How to find and replace text that is between certain keywords with javascript?
For example i have this text 例如我有这段文字
"!?vake 7EnEebjP8jXf JFyd5hpIVa6B !?vake".
The starting and ending keyword is "!?vake" and i want to retrieve the encrypted content between the keywords,decrypt it and replace it. 起始关键字和结束关键字为“!?vake”,我想检索关键字之间的加密内容,对其进行解密并替换。
The html code before replacing would be: 替换之前的html代码为:
<span class="messageBody" data-ft="{"type":3}">!?vake 7EnEebjP8jXf JFyd5hpIVa6B
Fu63LH23dAiB !?vake</span>
and after decrypting : 并在解密后:
<span class="messageBody" data-ft="{"type":3}">i am the decrypted text</span>
Replace should work in the whole html document without knowing the specific element the encrypted text is. 替换应该在整个html文档中起作用,而不需要知道加密文本的特定元素。
You can achieve this using RegExp. 您可以使用RegExp来实现。 See a demo here : http://jsfiddle.net/diode/KVqJS/4/ 在此处查看演示: http : //jsfiddle.net/diode/KVqJS/4/
var body = $("body").html();
var matched;
while ((matched = body.match(/!\?vake (.*?) !\?vake/))) {
if(matched.length > 1){
body = body.replace(/\!\?vake (.*) \!\?vake/, decode(matched[1]));
}
}
$("body").html(body);
function decode(encoded) {
return "decoded " + encoded;
}
You can use regex to find (and replace) the data. 您可以使用正则表达式查找(并替换)数据。
Here is a quick and dirty JSFiddle: http://jsfiddle.net/z8rVc/1/ 这是一个快速而肮脏的JSFiddle: http : //jsfiddle.net/z8rVc/1/
I'm sure someone will come up with a more elegant method, however. 我敢肯定,有人会想出一种更优雅的方法。
You can use the following regex search and replace code in JS: 您可以使用以下正则表达式搜索并替换JS中的代码:
var a = "!?vake 7EnEebjP8jXf JFyd5hpIVa6B !?vake";
var b = a.replace(/\!\?vake(.*)\!\?vake/g, '$1');
/// b contains your string between the keywords which you can decrypt as required.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.