簡體   English   中英

在JavaScript中刪除換行符

[英]Removing newline character in javascript

我在textarea中有一個文本,並使用.val()屬性獲取值。 我想刪除換行符(這是雙倍空格)嗎?

我嘗試使用.replace

sampleText = sampleText.replace(/(\r\n|\n|\r)/gm,"");

但這並沒有給我正確的解決方案。

我的文本區域的示例文本 在此處輸入圖片說明

當我嘗試.replace() ,它會像這樣

在此處輸入圖片說明

我如何去除樣品2和樣品3之間的空間? 它應該看起來像這樣。 在此處輸入圖片說明

按新行分割,濾除空行,最后加入

sampleText = sampleText.split(/\n|\r/).filter(function(value){
  return value.trim().length > 0;
}).join("\n");

 var sampleText = "Sample 1\\nSample 2\\n\\nSample 3"; sampleText = sampleText.split("\\n").filter(function(value){ return value.trim().length > 0; }).join("\\n"); document.write('<pre>'+sampleText+'</pre>'); 

您需要通過在組過濾上使用+號來加倍處理,以僅包括兩次出現的事件,並且不要用空字符串而是用新換行符代替它們。
有關加號的更多信息,我建議閱讀http://www.regular-expressions.info/repeat.html

這樣,每次重復出現都會被一次出現代替,這是您想要的

 var sampleText = "Sample1\\n\\nSample2\\n\\r\\n\\r\\r\\r\\nSample3"; document.write('<pre>Before:\\n'+sampleText); // The plus makes sure the matched pattern is repetitive and keeps replacing the doubles sampleText = sampleText.replace(/(\\r\\n|\\n|\\r)+/gm,"\\r\\n"); document.write('\\n\\nAfter:\\n'+sampleText+'</pre>'); 

您可以替換兩個換行符:

 var sampleText = "Sample1\\nSample2\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nSample3"; sampleText = sampleText.replace(/(\\n){2,}/gm, "\\n"); // matches 2 linebreaks to infinity; document.querySelector('pre').innerHTML = sampleText; 
 <pre></pre> 

或者僅使用.join()同時使用.split()從字符串中創建數組:

 var sampleText = "Sample1\\nSample2\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nSample3".split(/\\n{2,}/gm).join('\\n') document.querySelector('pre').innerHTML = sampleText; 
 <pre></pre> 

暫無
暫無

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

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