Reputation: 20875
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?
Upvotes: 0
Views: 173
Reputation: 1438
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);
Upvotes: 0
Reputation: 1485
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,'');
Upvotes: 2