2013-10-10 20 views
3

根據htmlcompressor.com的作者,這不能完成,因爲它們具有語義意義。如何從html屬性值中刪除字符?

下面是具體的例子:

<meta name='description' content='Foo lets you save and share all your 
    web bookmarks/favorites in one place. It is free with no advertising for life, and 
    has straight forward privacy controls.'> 

刪除你有返回字符:

<meta name='description' content='Foo lets you save and share all your web bookmarks/favorites in one place. It is free with no advertising for life, and has straight forward privacy controls.'> 

這是一個單一的線,就是我要發送給瀏覽器。

我想使用一些字符串操作我所有的HTML做到這一點。這有可能做或有其他情況下返回字符有意義嗎?有沒有辦法區分?

+0

'白色空間:pre'任意CSS在一般情況下使這不可能的。 – SLaks

+0

返回字符肯定有時候是重要的。例如,在'pre'中。或者,如果返回字符是分隔兩個元素的唯一事物。 –

+0

所以它並不簡單,需要用正則表達式來區分有意義和無意義的空白。 –

回答

2

按照HTML4.01規範(http://www.w3.org/TR/html4/struct/global.html#h-7.4.4.2)時,<meta />元件的content=""屬性是CDATA,這意味着空白是未顯著:

CDATA是一個字符從文檔字符集的序列並可能包含字符實體。用戶代理應該如下解釋的屬性值:

  • 與字符替換字符實體,
  • 忽略換行符,
  • 替換爲單個空格每個回車或標籤。
  • 用戶代理可能會忽略CDATA屬性值中的前導和尾隨空白(例如,「myval」可能會被解釋爲「myval」)。作者不應該使用前導空白或尾隨空白聲明屬性值。

因此,它看起來像htmlcompression的作者是錯誤的。

反正despite dire warnings to the contrary,你也許可以接應使用正則表達式來解決這個問題。

我忘了語法結合「僅匹配該組,該子區域替換」正則表達式中,但這個技巧的工作原理:

這個簡單的正則表達式將捕獲content=""屬性的內容:

<meta.+content='(.*)'> 

一旦你得到了內容,你可以做一個簡單的'\r', '\n', ' ' -> ' '替換。

0

每當說明書是關於內容屬性是CDATA正確,網站管理員可使用任何屬性的值,如在給定的例子通過JavaScript「元」標籤的「內容」,和壓縮所述屬性的值將改變預期的結果。

所以htmlcompressor.com的作者是正確的,因爲它們有壓縮的目的語意。

<meta id="m1" name="item1" content="Sample stuff: 

    1. This text is multiline on purpose. 
    2. And the author expects it to remain this way after compression. 

    So yes, it does matter..."> 

相同的元標記壓縮:

<meta id="m2" name="item2" content="Sample stuff: 1. This text is multiline on purpose. 2. And the author expects it to remain this way after compression. So yes, it does matter..."> 

而且以示區別:

<script> 
    alert('"' 
     + document.getElementById('m1').content 
     + '"\n\n---------------\n\n"' 
     + document.getElementById('m2').content + '"' 
); 
</script> 

據我所知,該網站的目標是壓縮文件,而不改變所產生的佈局或功能。

活生生的例子:http://jsfiddle.net/7Qb74/