user6002037
user6002037

Reputation:

trimming white space at end of lines javascript

I am running a js file through a minifier which is leaving line breaks at unexplained positions.

For example currently I have the following code:

var example = "var name = 'john';
               function sayName () {
                 alert('hi');
               }
               var person = {
                 name: 'peter',
                 sayName: function() {
                    alert('this is my name ' + this.name);
                 }
               }"

After it is run through the minifier I get:

var name='john';function sayName(){alert('hi');}
var person={name:'peter',sayName:function(){alert('this is my name '+this.name);}}

I have tried many regex and trim() but cannot figure out how to fix this. Does anyone have an idea of how to remove the white lines at the end of a line?

Upvotes: 0

Views: 738

Answers (1)

Philipp Dahse
Philipp Dahse

Reputation: 748

Try something like this:

var withoutWhitespaceAtLineEnd = example.split(/\n/).map(function(line){
  return line.replace(/\s+$/,'');
}).join("\n");

Upvotes: 0

Related Questions