dangerChihuahua007
dangerChihuahua007

Reputation: 20875

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. 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

Answers (3)

Tobi
Tobi

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

Zuuum
Zuuum

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

sikander
sikander

Reputation: 2286

Try:

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

Upvotes: 4

Related Questions