preserve non-breaking spaces during collapseWhitespace
authoralexlamsl <alexlamsl@gmail.com>
Wed, 8 Feb 2017 01:09:29 +0000 (09:09 +0800)
committeralexlamsl <alexlamsl@gmail.com>
Wed, 8 Feb 2017 01:09:29 +0000 (09:09 +0800)
fixes #777
replaces #184

src/htmlminifier.js
tests/minifier.js

index 431281b..cbfa953 100644 (file)
@@ -21,21 +21,21 @@ var trimWhitespace = String.prototype.trim ? function(str) {
 };
 
 function compressWhitespace(spaces) {
-  return spaces === '\t' ? spaces : ' ';
+  return spaces === '\t' ? '\t' : ~spaces.indexOf('\xA0') ? '\xA0' : ' ';
 }
 
 function collapseWhitespaceAll(str) {
-  return str ? str.replace(/[\t\n\r ]+/g, compressWhitespace) : str;
+  return str ? str.replace(/\s+/g, compressWhitespace) : str;
 }
 
 function collapseWhitespace(str, options, trimLeft, trimRight, collapseAll) {
   var lineBreakBefore = '', lineBreakAfter = '';
 
   if (options.preserveLineBreaks) {
-    str = str.replace(/^[\t ]*[\n\r][\t\n\r ]*/, function() {
+    str = str.replace(/^\s*?[\n\r]\s*/, function() {
       lineBreakBefore = '\n';
       return '';
-    }).replace(/[\t ]*[\n\r][\t\n\r ]*$/, function() {
+    }).replace(/\s*?[\n\r]\s*$/, function() {
       lineBreakAfter = '\n';
       return '';
     });
index dd7ec27..85aa4b0 100644 (file)
@@ -323,6 +323,9 @@ QUnit.test('space normalization around text', function(assert) {
   input = '<head> <!-- a --> <!-- b --> <!-- c --><link> </head>';
   output = '<head><!-- a --><!-- b --><!-- c --><link></head>';
   assert.equal(minify(input, { collapseWhitespace: true }), output);
+  input = '<p> foo\u00A0bar\nbaz  \u00A0\nmoo\t</p>';
+  output = '<p>foo\u00A0bar baz\u00A0moo</p>';
+  assert.equal(minify(input, { collapseWhitespace: true }), output);
 });
 
 QUnit.test('doctype normalization', function(assert) {
@@ -2315,6 +2318,12 @@ QUnit.test('conservative collapse', function(assert) {
     collapseWhitespace: true,
     conservativeCollapse: true
   }), output);
+
+  input = '<p>\u00A0</p>';
+  assert.equal(minify(input, {
+    collapseWhitespace: true,
+    conservativeCollapse: true
+  }), input);
 });
 
 QUnit.test('collapse preseving a line break', function(assert) {