簡體   English   中英

從 textarea 中刪除帶有換行符的方大括號內的內容

[英]Remove content within square curly brackets with linebreak from textarea

我在創建論壇帖子頁面上有以下文本區域。

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.

當用戶填寫表單時,機密信息會自動粘貼到 textarea 中。 但現在我想添加一個按鈕,允許在沒有網站詳細信息的情況下發布。 但仍然允許機密信息。

就個人而言,我在正則表達式方面很糟糕。 看着那些對我來說就像魔術一樣。 但我很確定這正是我所需要的。 所以我現在正在嘗試使用下面的代碼,但這是隨機刪除所有內容。

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);

我真的希望有人能幫我從 textarea 中刪除這部分,但保留其他所有內容:

需要移除

[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.

這些部分是需要刪除的部分的開始和結束。 請記住,textarea 中有換行符(回車)

開始

[confidential]
{sitedetails}

結尾

{/sitedetails}
[/confidential]

你想要的正則表達式是/\\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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM