[英]Remove carriage return and space from a string
我想从字符串中删除回车符和空格例如:
var t =" \n \n aaa \n bbb \n ccc \n";
我希望得到结果:
t = "aaa bbb ccc"
我使用这个,它删除回车但我仍然有空格
t.replace(/[\n\r]/g, '');
请有人帮助我。
尝试:
t.replace(/[\n\r]+/g, '');
然后:
t.replace(/\s{2,10}/g, ' ');
第二个应该摆脱超过1个空间
或者你可以使用单正则表达式:
t.replace(/\s+/g, ' ')
此外,由于前导和尾随空格,您需要调用.trim()
。 所以完整的将是:
t = t.replace(/\s+/g, ' ').trim();
我会建议
从而
t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'')
太棒了! 感谢分享Ulugbek。 我使用以下代码从条形码扫描仪中获取逗号分隔值。 只要按下条形码扫描仪按钮,回车符和空格就会转换为逗号。
Java脚本:
function KeyDownFunction() {
var txt = document.getElementById("<%=txtBarcodeList.ClientID %>");
txt.value = txt.value.replace(/\s+/g, ',').trim();
}
标记:
<asp:TextBox ID="txtBarcodeList" runat="server" TextMode="MultiLine" Columns="100"
Rows="6" onKeyDown="KeyDownFunction()"></asp:TextBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.