Подтвердить что ты не робот

Подстроить текст с помощью HTML-тегов в Javascript

У вас есть решение для подстроки текста с тегами HTML в Javascript?

Например:

var str = 'Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, consectetur adipiscing elit.'

html_substr(str, 20)
// return Lorem ipsum <a href="#">dolor <strong>si</strong></a>

html_substr(str, 30)
// return Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, co
4b9b3361

Ответ 1

Принимая во внимание, что разбор html с регулярным выражением - плохая идея, вот решение, которое делает именно это:)

EDIT: просто чтобы быть ясным: это не действительное решение, оно предназначалось как упражнение, которое делало очень мягкие предположения о входной строке и как таковое должно приниматься с солью. Прочитайте приведенную выше ссылку и посмотрите, почему анализ синтаксического анализа html с помощью регулярного выражения никогда не будет выполнен.

function htmlSubstring(s, n) {
    var m, r = /<([^>\s]*)[^>]*>/g,
        stack = [],
        lasti = 0,
        result = '';

    //for each tag, while we don't have enough characters
    while ((m = r.exec(s)) && n) {
        //get the text substring between the last tag and this one
        var temp = s.substring(lasti, m.index).substr(0, n);
        //append to the result and count the number of characters added
        result += temp;
        n -= temp.length;
        lasti = r.lastIndex;

        if (n) {
            result += m[0];
            if (m[1].indexOf('/') === 0) {
                //if this is a closing tag, than pop the stack (does not account for bad html)
                stack.pop();
            } else if (m[1].lastIndexOf('/') !== m[1].length - 1) {
                //if this is not a self closing tag than push it in the stack
                stack.push(m[1]);
            }
        }
    }

    //add the remainder of the string, if needed (there are no more tags in here)
    result += s.substr(lasti, n);

    //fix the unclosed tags
    while (stack.length) {
        result += '</' + stack.pop() + '>';
    }

    return result;

}

Пример: http://jsfiddle.net/danmana/5mNNU/

Примечание: решение patrick dw может быть более безопасным в отношении плохого html, но я не уверен, насколько хорошо он обрабатывает пробелы.

Ответ 2

это решение для отдельных тегов

function subStrWithoutBreakingTags(str, start, length) {
    var countTags = 0;
    var returnString = "";
    var writeLetters = 0;
    while (!((writeLetters >= length) && (countTags == 0))) {
        var letter = str.charAt(start + writeLetters);
        if (letter == "<") {
            countTags++;
        }
        if (letter == ">") {
            countTags--;
        }
        returnString += letter;
        writeLetters++;
    }
    return returnString;
}

Ответ 3

Использование:

var str = 'Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, consectetur adipiscing elit.';

var res1 = html_substr( str, 20 );
var res2 = html_substr( str, 30 );

alert( res1 ); // Lorem ipsum <a href="#">dolor <strong>si</strong></a>
alert( res2 ); // Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, co

Пример: http://jsfiddle.net/2ULbK/4/


Функции:

function html_substr( str, count ) {

    var div = document.createElement('div');
    div.innerHTML = str;

    walk( div, track );

    function track( el ) {
        if( count > 0 ) {
            var len = el.data.length;
            count -= len;
            if( count <= 0 ) {
                el.data = el.substringData( 0, el.data.length + count );
            }
        } else {
            el.data = '';
        }
    }

    function walk( el, fn ) {
        var node = el.firstChild;
        do {
            if( node.nodeType === 3 ) {
                fn(node);
                    //          Added this >>------------------------------------<<
            } else if( node.nodeType === 1 && node.childNodes && node.childNodes[0] ) {
                walk( node, fn );
            }
        } while( node = node.nextSibling );
    }
    return div.innerHTML;
}

Ответ 4

let str = 'Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, consectetur adipiscing elit.'
let plainText = htmlString.replace(/<[^>]+>/g, '');

Извлеките обычный текст с помощью указанного выше регулярного выражения, затем используйте функцию ".substr()" на основе JS String для получения желаемых результатов.

Ответ 5

Вы можете использовать библиотеку JavaScript для этого: html-substring.

Ответ 7

Используйте что-то похожее на = str.replace(/<[^>]*>?/gi, '').substr(0, 20);
Я создал пример: http://fiddle.jshell.net/xpW9j/1/