简体   繁体   English

如何可靠地删除JavaScript字符串中的新行?

[英]How can I reliably take away the new lines in a javascript string?

I am trying to remove the new lines in a javascript string. 我正在尝试删除JavaScript字符串中的新行。 http://jsfiddle.net/muT5V/ http://jsfiddle.net/muT5V/

However, the alert box produced from this code (jQuery is included) still retains the new lines. 但是,从此代码(包括jQuery)产生的警报框仍保留新行。

My javascript: 我的JavaScript:

var s = $('#aDivWithContent').html();
s = s.replace('\n', '').replace('\s', '');
alert(s);​

My HTML: 我的HTML:

<div id="aDivWithContent">
    <ul>
        <li>foo</li>
        <li>bar</li>
        <li>baz</li>
    </ul>
</div>​

Why? 为什么?

尝试:

s = s.replace(/(\r\n|\n|\r|\t|\s)/gm,"");

You need RegExp with g option and \\r cleanup 您需要带有g选项和\\ r清理的RegExp

var r = new RegExp("\\r", "g"); var r = new RegExp(“ \\ r”,“ g”);

var n = new RegExp("\\n", "g"); var n = new RegExp(“ \\ n”,“ g”);

str = str.replace(r,'').replace(n,''); str = str.replace(r,'')。replace(n,'');

The Reason is, that replace() only replaces ONE found. 原因是,replace()仅替换找到的一个。 If you use a RegEx as first parameter from replace(), then all found results will be replaced. 如果您使用RegEx作为replace()的第一个参数,则将替换所有找到的结果。

var s = $('#aDivWithContent').html();
s = s.replace(new RegExp("\n", "g"), 'a');
s = s.replace(new RegExp("\s", "g"), 'b');

alert(s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM