包含跨越尊重标签的行

时间:2013-04-12 11:44:46

标签: jquery string split

我需要在单独的跨度中将文本换行。
我找到了一个(几乎)完全符合我需要的答案......

  

plugin to wrap text example

$.fn.wrapLines = function (options) {
    var options = $.extend({
        lineWrap: 'span',
        lineClassPrefix: 'wrapliner wrap_line_',
        wordClassPrefix: 'w_line_',
        index: 0,
        offsetTop: 0,
        offsetLeft: 0
    }, options);
    return this.each(function () {
        options.index = 0;
        options.offset = 0;
        var parentElm = $(this);
        var elmText = $(parentElm).text();
        $(parentElm).html(function (ind, htm) {
            var $repText = '<' + options.lineWrap + '>' + elmText.replace(/\s+/g, ' </' + options.lineWrap + '> <' + options.lineWrap + '>');
            $repText = $repText + '</' + options.lineWrap + '>';
            return $repText;
        });
        $(options.lineWrap, parentElm).each(function () {
            var spanOffset = $(this).offset();
            if (spanOffset.top > options.offsetTop) {
                options.offsetTop = spanOffset.top;
                options.index++;
            }
            $(this).addClass(options.wordClassPrefix + options.index);
        });

        if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 8)) {
            for (var x = 1; x <= options.index; x++) {
                var $spans = $('.' + options.wordClassPrefix + x);
                $spans
                .eq($spans.length - 1)
                .removeClass(options.wordClassPrefix + x)
                .addClass(options.wordClassPrefix + (x + 1))
            }
        }
        for (var x = 1; x <= options.index; x++) {
            $('.' + options.wordClassPrefix + x, parentElm)
            .wrapAll('<' + options.lineWrap + ' class="' + options.lineClassPrefix + x + '" />')
            .append("");
            var innerText = $('.' + options.lineClassPrefix + x, parentElm).text();
            $('.' + options.lineClassPrefix + x, parentElm).html(function () {
                return innerText;
            });
        }
    });
};

然而,我想保留标签。

我尝试将.text更改为.html并调整正则表达式,但我似乎无法找到答案。 ......我不是正则表达式的专家

也许有人可以帮我解决这个问题。

这是我当前实现的一个小提琴,只能获取文本。

  

only use Text jsFiddle

这是一个保留标签的小提琴,但不会正确地将标签包裹在

之前
  

does not wrap before tags jsFiddle

这是我找到的另一个例子。它完美地包装了单词,但没有包裹行

  

wrap Words preserving tags jsFiddle

1 个答案:

答案 0 :(得分:0)

所以我终于找到了正确的模式。

  
    

workin jsFiddle

  

这是我使用的模式/(<\s*.*?[^>]*>(.*?)<\s*\s*.*?>)|(\s+)/ig

// returns all spaces or tags with their content
.replace(/(<\s*.*?[^>]*>(.*?)<\s*\s*.*?>)|(\s+)/ig, '$1') 

这仍然不完美,因为它不会允许在子标签内部打破线条,但是出于我的特定原因,它可以满足我的需求。

也许有人可以使用它。

仍然期待其他实施。

相关问题