Question

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.

Was it helpful?

Solution

Try:

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

Then:

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

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

OTHER TIPS

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

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+$/,'') 

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top