【问题标题】:Remove carriage return and space from a string从字符串中删除回车符和空格
【发布时间】:2014-05-20 05:12:22
【问题描述】:

我想从字符串中删除回车和空格 例如:

var t ="     \n \n    aaa \n bbb \n ccc \n";

我想得到结果:

t = "aaa bbb ccc"

我用这个,它去掉了回车但我还有空格

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

请有人帮助我。

【问题讨论】:

  • 添加 \s 到它:/[\s\n\r]/g
  • @vp_arth 如果\s 已经匹配它们,那么包含\n\r 有什么意义?
  • 也许我错了...我记得一些关于 lineends 和 global flag.. 可能是关于一个点?对不起)

标签: javascript regex space carriage-return


【解决方案1】:

试试:

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

然后:

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

第二个应该去掉超过 1 个空格

【讨论】:

    【解决方案2】:

    或者您可以使用单个正则表达式:

    t.replace(/\s+/g, ' ')
    

    由于前导和尾随空格,您还需要调用.trim()。所以完整的将是:

    t = t.replace(/\s+/g, ' ').trim();
    

    【讨论】:

    • 我仍然为此调用 replace(/^\s+|\s+$/g,'') :) 需要查看更新)
    • @tenub 我用单个空格替换多个空格。因此,如果有前导空格,就会有前导空格。如果有尾随空格,则将有尾随空格。我们使用.trim() 摆脱它们。编辑:哎呀,@tenub 已经删除了这个问题。
    • 这对我有用,而 other popular answer 没有抓住我的情况。
    【解决方案3】:

    太棒了!感谢分享乌鲁别克。我使用以下代码从条形码扫描仪中获取逗号分隔值。每当按下条形码扫描仪按钮时,回车和空格都会转换为逗号。

    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>
    

    【讨论】:

      【解决方案4】:

      建议

      • 清除回车=>空格
      • 用一个空格替换多个空格
      • 清除前导和尾随空格(与 jQuery trim() 相同)

      这样

      t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'') 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-19
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 2011-09-21
        • 1970-01-01
        • 2021-10-16
        • 2014-08-17
        相关资源
        最近更新 更多