繁体   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