I am trying to remove the new lines in a javascript string. http://jsfiddle.net/muT5V/
However, the alert box produced from this code (jQuery is included) still retains the new lines.
My javascript:
var s = $('#aDivWithContent').html();
s = s.replace('\n', '').replace('\s', '');
alert(s);
My 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
var r = new RegExp("\\r", "g");
var n = new RegExp("\\n", "g");
str = str.replace(r,'').replace(n,'');
The Reason is, that replace() only replaces ONE found. If you use a RegEx as first parameter from replace(), then all found results will be replaced.
var s = $('#aDivWithContent').html();
s = s.replace(new RegExp("\n", "g"), 'a');
s = s.replace(new RegExp("\s", "g"), 'b');
alert(s);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.