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