2015-06-26 53 views
2

我想將所有大寫字母和撇號定位到一個html字符串,並省略所有的html標籤。事實上,兩個ra子之間的內容瞄準是不可取的,因爲它會導致錯誤。正則表達式jQuery:找到大寫字母並忽略html標籤

串的例子的問題:

實施例1:

Test Drop Cap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777">Span</span> and more text<a href="#index-anchor" class="anchor"></a> 

實施例2:

Test Drop Cap with a <a href="https://github.com/Scriptura/Scriptura">Link</a> and that's it 

預期輸出是:

實施例1:

<span class="letter">T</span>est <span class="letter">D</span>rop <span class="letter">C</span>ap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777"><span class="letter">S</span>pan</span> and more text<a href="#index-anchor" class="anchor"></a> 

例2:

<span class="letter">T</span>est <span class="letter">D</span>rop <span class="letter">C</span>ap with a <a href="https://github.com/Scriptura/Scriptura"><span class="letter">L</span>ink</a> and that's it 

現在我做到這一點:

(function($){ 
    $.fn.letter = function(){ 
     $(':header, legend, .h1, .h2, .h3, .h4, .h5, .h6, .addletter').each(function(){ 
      var string = $(this); 
      var newString = string.html().replace(/(<([^>]+)>|[A-Z«»"]|&amp;)/gm, '<span class="letter">$1</span>'); 
      string.html(newString); 
     }); 
    }; 
    $('.letter').letter(); 
})(jQuery); 

但我的正則表達式是不完美:它也是針對兩個標記之間的內容。你能幫我做一個更好的正則表達式嗎?謝謝。

+0

@阿維納什拉吉:謝謝你的澄清請求。我剛剛更新了我的帖子。 –

回答

1

您可以使用這種基於負面預測的正則表達式。

string.replace(/([A-Z])(?![^<>]*>)/g, '<span class="letter">$1</span>'); 

DEMO

var s = 'Test Drop Cap with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes">Link</a> & a <span style="color:#777">Span</span> and more text<a href="#index-anchor" class="anchor"></a>'; 
 
alert(s.replace(/([A-Z])(?![^<>]*>)/g, '<span class="letter">$1</span>'))

+1

謝謝。這正是我尋找的解決方案! –

+1

不客氣..如果您發佈了預期的輸出結果,您應該在20分鐘之前獲得解決方案。 –

+0

我想未來,謝謝。 –