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.

3
  • add \s to it: /[\s\n\r]/g
    – vp_arth
    Apr 7, 2014 at 19:33
  • @vp_arth what's the point to include \n and \r if \s already matches them? Apr 7, 2014 at 19:40
  • Maybe I wrong... I remember some about lineends and global flag.. may be about a point? sorry)
    – vp_arth
    Apr 7, 2014 at 19:44

4 Answers 4

61

Try:

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

Then:

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

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

0
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();
3
  • and I still call replace(/^\s+|\s+$/g,'') for this :) Need to review updates)
    – vp_arth
    Apr 7, 2014 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. Apr 7, 2014 at 19:50
  • This worked for me whereas the other popular answer did not catch my case.
    – Chiramisu
    Jun 29, 2019 at 1: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+$/,'') 
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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.