[英]Removing newline character in javascript
按新行分割,濾除空行,最后加入
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.