简体   繁体   中英

Removing newline character in javascript

I have a text in a textarea and get the value using the .val() attribute. I would like to remove the linebreaks (which is the doublespace)?

i tried using the .replace

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

But it did not give me the correct solution.

sample text from my textarea 在此处输入图片说明

when i tried the .replace() , it will do like this

在此处输入图片说明

how do i remove the space between sample 2 and sample 3? it should look like this.. 在此处输入图片说明

split by new line, filter out an empty line and finally join

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

Example

 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>'); 

You need to double up on your by using the + sign on your group filtering to only include the double occurences, and don't replace them with an empty string but with a new newline.
For more information about the plus sign I recommend to read http://www.regular-expressions.info/repeat.html

This way every double occurence will be replaced by a single occurence, which is what you want I guess

 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>'); 

You can do the replacement of two line breaks:

 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> 

Or just with .join() while creating an array out of string with .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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM