我想将所有大写字母和撇号定位为html字符串,并省略所有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«»"]|&)/gm, '<span class="letter">$1</span>');
string.html(newString);
});
};
$('.letter').letter();
})(jQuery);
但我的正则表达并不完美:它还针对两个标签之间的内容。你能帮我做一个更好的正则表达式吗?谢谢。
答案 0 :(得分:1)
你可以使用这种基于正则表达式的负向前瞻。
string.replace(/([A-Z])(?![^<>]*>)/g, '<span class="letter">$1</span>');
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>'))