目前我正在文本區域內輸入文本,并在單擊表單的提交按鈕時,主要使用 .replaceAll(); 對文本進行一些更改;js 方法并將其作為 div 中的段落列印出來。
如果我在文本區域中輸入已經有換行符和括號的文本,我希望我的腳本去除/洗掉所有括號以及括號內的內容,并保持所有換行符不變。
我已經使用示例文本嘗試了以下 regex js 函式,但是引入了一些格式問題(洗掉了一些換行符,括號后的文本與洗掉括號的前一行中的文本位于同一行)
正則運算式 js代碼:
updatedText = updatedText.replaceAll(/\s*\(.*?\)\s*/g, '');
樣本輸入:
06.abbaa(bbbbadf)
01.lijer ttt
06.foo(sample)dddddddddd(garbage)
06.text(lksdhfljkld)20001(kkkkkksssss)
01.asdfg
13.fffffffff(fdsgggg/asdfasdf)
03.ggggggg(defg/abc)
18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh(moreblah/blah)
15.2035number(test)(test0/2test)
12.testing morewords
03.random(blahhh)(blahahaha/morerandomstuff)
17.anotherrandomtextstring
11.string
testy(mctest)
isTestingStrings
11.string
11.string
11.string
在不應該合并行時輸出的結果是:
06.abbaa01.lijer ttt
06.foodddddddddd06.text2000101.asdfg
13.fffffffff03.ggggggg18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh15.2035number12.testing morewords
03.random17.anotherrandomtextstring
11.string
testyisTestingStrings
11.string
11.string
11.string
- 例如,“testy”和“isTestingStrings”應該在 2 個單獨的行上。
- 每行可以有任意數量的(0 個或更多)“(xxxx ...)”括號和內容,在這些情況下也應該保留換行符。
為什么用空字串替換匹配的文本會導致從字串中洗掉換行符,以及如何在我的腳本中解決此問題。是否有更好的正則運算式來處理這個問題,或者這是否需要撰寫一個自定義的 js 決議器?
uj5u.com熱心網友回復:
您是否嘗試過以下操作?
inputString.replace(/\([^)]*\)/g,"")
s=`06.abbaa(bbbbadf)
01.lijer ttt
06.foo(sample)dddddddddd(garbage)
06.text(lksdhfljkld)20001(kkkkkksssss)
01.asdfg
13.fffffffff(fdsgggg/asdfasdf)
03.ggggggg(defg/abc)
18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh(moreblah/blah)
15.2035number(test)(test0/2test)
12.testing morewords
03.random(blahhh)(blahahaha/morerandomstuff)
17.anotherrandomtextstring
11.string
testy(mctest)
isTestingStrings
11.string
11.string
11.string`;
console.log(s.replace(/\([^)]*\)/g,""))
uj5u.com熱心網友回復:
從字串中洗掉新換行符的原因是換行符被認為是空格字符,并且\s在正則運算式中與這兩個字符匹配。如果要保留換行符但要洗掉括號前后的空格和制表符,請更改\s為[\t ]:
updatedText = updatedText.replaceAll(/[\t ]*\(.*?\)[\t ]*/g, '');
如果您從未打算洗掉空格字符,而只想洗掉括號以及其中的文本,則只需\s*從您的正則運算式中洗掉序列:
updatedText = updatedText.replaceAll(/\(.*?\)/g, '');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405405.html
標籤:
上一篇:使用節點快遞運行服務器角度
