首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除方括号内的内容,并从文本区域中删除换行符

删除方括号内的内容,并从文本区域中删除换行符
EN

Stack Overflow用户
提问于 2019-06-24 13:27:58
回答 1查看 51关注 0票数 0

我有以下的文本区域在一个创建论坛贴子页。

代码语言: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.

当用户填写表单时,机密信息将自动粘贴到文本区域。但现在我想添加一个按钮,允许张贴没有网站的细节。但仍然允许机密信息。

就我个人而言,我不擅长正则表达式。看着那些,对我来说就像魔法一样。但我很确定这正是我所需要的。所以,我现在正在尝试下面的代码,但这是删除所有东西,但不随机。

代码语言:javascript
复制
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);

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

需要移除

代码语言:javascript
复制
[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]

结果是这样的

代码语言:javascript
复制
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.

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

开始

代码语言:javascript
复制
[confidential]
{sitedetails}

结束

代码语言:javascript
复制
{/sitedetails}
[/confidential]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-24 13:58:02

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

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

但我很确定这正是我所需要的。

Regex很少是必要的,它是一个方便的工具,但是您也可以轻松地用新的行拆分文本,拼接出子数组,然后重新连接到一个字符串中。

代码语言:javascript
复制
    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);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56737640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档