[英]Remove carriage return and space from a string
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. 请有人帮助我。
Try: 尝试:
t.replace(/[\n\r]+/g, '');
Then: 然后:
t.replace(/\s{2,10}/g, ' ');
The 2nd one should get rid of more than 1 space 第二个应该摆脱超过1个空间
Or you can do using single regex: 或者你可以使用单正则表达式:
t.replace(/\s+/g, ' ')
Also you will need to call .trim()
because of leading and trailing spaces. 此外,由于前导和尾随空格,您需要调用
.trim()
。 So the full one will be: 所以完整的将是:
t = t.replace(/\s+/g, ' ').trim();
I would suggest 我会建议
Thus 从而
t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'')
Fantastic! 太棒了! thanks for sharing Ulugbek.
感谢分享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: Java脚本:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.