簡體   English   中英

Javascript正則表達式,刪除單段換行符

[英]Javascript regex, make remove single paragraph line breaks

我有這種格式的文字:

word word,
word word.

word word
word word.

不是特定於那兩個單詞格式,它只是在這么多字符之前的換行符,而不是一個長串的段落。 但我試圖讓它成為一段長長的段落。 所以看起來應該是這樣的:

word word, word word.
word word word word.

如果我使用代碼text.replace(/$\\n(?=.)/gm, " ")並將其輸出到終端,我會得到如下所示的文本:

 word word, word word.
 word word word word.

它在段落的開頭有一個額外的空間,但這對我正在嘗試做的事情已經足夠好了(盡管如果還有一種方法可以在一個替換函數中刪除它而不是那個好的)。 問題是,當我將它輸出到textarea時,它不會刪除\\ n字符,我只是得到如下所示的文本:

 word word,
 word word.

 word word
 word word.

我試圖在所有客戶端執行此操作,目前在Firefox中運行它。

我不是最好的正則表達式,所以這可能非常簡單,我只是不知道如何做到這一點。 但任何幫助都會非常感激。 謝謝!

回車是\\ r \\ n所以你需要使用

 text.replace(/$(\\r|\\n)(?=.)/gm, " "); 

你可能錯過了一些\\ r \\ n,這里有一種方法可以匹配所有類型的新行並且沒有額外的空格:

 var input = 'word word,\\nword word.\\n\\nword word\\nword word.'; // split if 2 or more new lines var out = input.split(/(\\r\\n|\\n|\\r){2,}?/) // split the paragraph by new lines and join the lines by a space .map((v) => v.split(/\\r\\n|\\n|\\r/).join(' ')) // there is some spaces hanging in the array, filter them .filter((v) => v.trim()) // join together all paragraphs by \\n .join('\\n'); $('#txt').append(out); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txt"></textarea> 

在滿足您的請求的代碼片段下方,我已經刪除了前導空格(由空行引起),使用帶有replace函數的閉包:

 var regex = /([^.])\\s+/g; var input = 'word word,\\nword word.\\n\\nword word\\nword word.'; var result = input.replace(regex, function(all, char) { return (char.match(/\\s/)) ? char : char + ' ' ; }); document.write('<b>INPUT</b> <xmp>' + input + '</xmp>'); document.write('<b>OUTPUT</b> <xmp>' + result + '</xmp>'); 

正則表達式突圍

([^.])        # Select any char that is not a literal dot '.'
              # and save it in group $1
\s+           # 1 or more whitespace char, remove trailing spaces (tabs too)
              # and all type of newlines (\r\n, \r, \n)

注意

如果由於某種原因你想保留前導空格,請簡化下面的代碼,如下所示:

 var regex = /([^.])\\s+/g; var replace = '$1 '; var input = 'word word,\\nword word.\\n\\nword word\\nword word.'; var result = input.replace(regex, replace); document.write('<b>INPUT</b> <xmp>' + input + '</xmp>'); document.write('<b>OUTPUT</b> <xmp>' + result + '</xmp>'); 

暫無
暫無

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

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