Reputation: 421
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.
Upvotes: 38
Views: 74241
Reputation: 1712
I would suggest
Thus
t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'')
Upvotes: 5
Reputation: 51
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>
Upvotes: 0
Reputation: 12797
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();
Upvotes: 24
Reputation: 5197
Try:
t.replace(/[\n\r]+/g, '');
Then:
t.replace(/\s{2,10}/g, ' ');
The 2nd one should get rid of more than 1 space
Upvotes: 62