37

I want to remove carriage return and space from a string for exemple:

var t ="     \n \n    aaa \n bbb \n ccc \n";

I want to have as result:

t = "aaa bbb ccc"

I use this one, it removes carriage return but I still have spaces

t.replace(/[\n\r]/g, '');

Please someone help me.

Guest Guest
  • 411
  • 1
  • 6
  • 9

4 Answers4

60

Try:

 t.replace(/[\n\r]+/g, '');

Then:

 t.replace(/\s{2,10}/g, ' ');

The 2nd one should get rid of more than 1 space

Andrew Newby
  • 4,941
  • 6
  • 40
  • 81
24

Or you can do using single regex:

t.replace(/\s+/g, ' ')

Also you will need to call .trim() because of leading and trailing spaces. So the full one will be:

t = t.replace(/\s+/g, ' ').trim();
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
  • and I still call replace(/^\s+|\s+$/g,'') for this :) Need to review updates) – vp_arth Apr 07 '14 at 19:47
  • @tenub I replace multiple whitespaces with single space. So if there were leading whitespaces, there will be leading space. If there were trailing whitespaces, there will be trailing space. We get rid of them using `.trim()`. EDIT: oops, @tenub already deleted the question. – Ulugbek Umirov Apr 07 '14 at 19:50
  • This worked for me whereas the [other popular answer](https://stackoverflow.com/a/22921273/836169) did not catch my case. – Chiramisu Jun 29 '19 at 01:19
4

I would suggest

  • to clear carriage return => space
  • to replace multiple spaces by a single one
  • to clear leading and trailing spaces (same as jQuery trim())

Thus

t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'') 
Open SEO
  • 1,682
  • 14
  • 16
0

Fantastic! thanks for sharing Ulugbek. I used the following code to have comma separated values from a barcode scanner. Anytime the barcode scanner button is pressed, carriage returns and spaces are converted to commas.

Java Script:

function KeyDownFunction() {
    var txt = document.getElementById("<%=txtBarcodeList.ClientID %>");
    txt.value = txt.value.replace(/\s+/g, ',').trim();
}

Markup:

<asp:TextBox ID="txtBarcodeList" runat="server" TextMode="MultiLine" Columns="100"
                    Rows="6" onKeyDown="KeyDownFunction()"></asp:TextBox>
Jesilo
  • 41
  • 1