从文本区域中删除带有换行符的方形花括号中的内容

时间:2019-06-24 13:27:58

标签: javascript

我在创建论坛帖子页面上有以下文本区域。

There is some text here in front:

[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

There is some text in the middle. 

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.

当用户填写表格时,机密信息会自动粘贴到文本区域中。但是现在我想添加一个按钮,该按钮允许发布而无需网站详细信息。但仍然允许机密信息。

就个人而言,我对正则表达式感到恐惧。看着那些对我来说就像魔术。但是我很确定这正是我所需要的。 因此,我现在尝试使用下面的代码,但这将随机删除所有内容。

var $editor = $(".markItUpEditor");
var curValue = $editor.val();
val = curValue;
val = val.replace(/'[confidential]'([\s\S]*)[\/confidential]/gm, "");
val = val.replace(/[[\]]/g,'')
$editor.val(val);
console.log(val);

我真的希望有人能帮助我从文本区域中删除此部分,但保留其他所有内容:

需要删除

[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

所以结果是这样的

There is some text here in front:

There is some text in the middle. 

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.

这些部分是需要删除的内容的开头和结尾。请记住,文本区域中有换行符(输入)

开始

[confidential]
{sitedetails}

结束

{/sitedetails}
[/confidential]

1 个答案:

答案 0 :(得分:1)

您想要的正则表达式为/\s*\[confidential\]\s*\{sitedetails\}(\s|\S)*{\/sitedetails\}\s*\[\/confidential\]\s*/g

这有点冗长,但是将鼠标悬停在regex101的每个部分上,以了解发生了什么:https://regex101.com/r/R5Oece/1

  

但是我很确定[regex]正是我所需要的。

正则表达式很少是必需的,它是一种便捷工具,但是您可以轻松地用新行将文本分割,拼接出子数组并重新连接为字符串。

    const str = `There is some text here in front:

[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

There is some text in the middle. 

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.`;

    let out = str.replace(/\s*\[confidential\]\s*\{sitedetails\}(\s|\S)*{\/sitedetails\}\s*\[\/confidential\]\s*/g, '\n\n');

    console.log(out);