gpt4 book ai didi

javascript - 仅替换 bbcode 标签内的多个字符,而不影响 bbcode 之外的任何其他文本

转载 作者:行者123 更新时间:2023-11-29 18:44:05 27 4
gpt4 key购买 nike

所以我创建了这个函数来替换字符串中的特殊字符。主要目的是替换 BBCode 标签内的那些特殊字符([code=any]我想显示的代码[/code]),但当时它是否替换其余部分并不重要BBcode 标签之外的字符串。但是现在我在替换 BBcode 标签之外的 HTML 标签时遇到了问题。所以我试图为此想出一个解决方案,但到目前为止还没有运气。

目标是替换里面的特殊字符:

[code=any]some code inside of here[/code]

还应该提到,当我说 code=any 时,意思是它可以是任何东西。它可以是 HTML、CSS、PHP、JS [a-z-A-Z-0-9]。

更像

[code=[a-z-A-Z-0-9]<h1>some html insode of the bbcode to be replace</h1>[/code]

我目前的功能很简单。只需要一些基本的正则表达式:

replaceSpecial : function(str) {

str = str.replace(/&/g, "&amp;");
str = str.replace(/>/g, "&gt;");
str = str.replace(/</g, "&lt;");
str = str.replace(/"/g, "&quot;");
str = str.replace(/'/g, "&#039;");

return str;
}

但是我将如何重写它,以便它只替换以下文本:[code=any]some code inside here[/code],仅此而已。如果有人对此有解决方案,那就太棒了。

谢谢你的时间,乔恩 W

最佳答案

您想提取条形码内的文本并应用此正则表达式,您可以使用 exec 将替换应用于代码中的内容,可以使用捕获组和反向引用查看更多链接 https://www.regular-expressions.info/refcapture.html

在这种情况下,只获取bbcode内部的文本并进行处理

let code = "[code=any]<h1>hello and bye</h1>e[/code]";
//extract only texto inside bbcode
let match = /\[code\=any\](.+)\[\/code\]/g.exec(code)[1];
//get <h1>hello</h1>e
let replacement = myObj.replaceSpecial(match);

enter image description here

参见 https://regex101.com/r/KGCWmq/1

这只是如果你想得到,如果你想替换你可以使用替换功能。

var myObj = {
replaceSpecial : function(str) {
str = str.replace(/&/g, "&amp;");
str = str.replace(/>/g, "&gt;");
str = str.replace(/</g, "&lt;");
str = str.replace(/"/g, "&quot;");
str = str.replace(/'/g, "&#039;");
return str;
}
};
let code = "[code=any]<h1>hello and bye</h1>e[/code]";
let match = /\[code\=any\](.+)\[\/code\]/g.exec(code)[1];
let replacement = myObj.replaceSpecial(match);
let string = code.replace(/\[code\=any\](.+)\[\/code\]/,"[code=any]"+replacement+"[/code]")

已更新

根据Wiktor Stribiżew的回答,可以验证正则表达式使得bbcode是任意的

myObj = {
replaceSpecial : function(str) {
return str.replace(/&/g, "&amp;")
.replace(/>/g, "&gt;")
.replace(/</g, "&lt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
}

var s = '[code="HTML"]<h1>Hello</h1>[/code]';
var regex = /(\[code=[^\]]*])([^]*?)(\[\/code])/gi;
console.log( s.replace(regex, function($0, $group_match1, $group_match2, $group_match3) { return $group_match1 + myObj.replaceSpecial($group_match2) + $group_match3; }) );

希望我对您有所帮助,如果不是您所期望的,请发表评论并编辑问题

关于javascript - 仅替换 bbcode 标签内的多个字符,而不影响 bbcode 之外的任何其他文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203658/

27 4 0