ap.singh
ap.singh

Reputation: 1160

Substring text with javascript including html tags

i wanted to substring a string something like follow. And i have start position and length of the string . i have checked this ques Substring text with HTML tags in Javascript. But in this substring is performing from 0 but i have a random start position. Any idea about how it will done

var str = 'Lorem ipsum <p>dolor <strong>sit</strong> amet</p>, consectetur adipiscing elit.'

Upvotes: 1

Views: 2612

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Here is a native DOM API approach to do this sort of thing. The browser already has powerful built in HTML parsing abilities. No need to re-invent the wheel

var el = document.createElement("div");
el.innerHTML = 'Lorem ipsum <p>dolor <strong>sit</strong> amet</p>, consectetur adipiscing elit.';
el.getElementsByTagName("p").textContent;

Working demo

The result is just a non-html string which you can easily manipulate with .substring

So, how did this work?

We dumped our HTML into an HTML element.

Then we used the DOM API to say the following:

"Inside the HTML we just gave you, find all p tags, take the first (that's the [0]), and give us its textContent".

Upvotes: 0

rahul maindargi
rahul maindargi

Reputation: 5655

Here is DEMO

function html_substr( str, start ,count ) {

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

    walk( div, track );

    function track( el ) {
        if( count > 0 ) {
            var len = el.data.length;
            if(start<=len){
                el.data = el.substringData(start,len);
                start=0;
            } else{
                start-=len;
                el.data = '';
            }
            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);
            } else if( node.nodeType === 1 && node.childNodes && node.childNodes[0] ) {
                walk( node, fn );
            }
        } while( node = node.nextSibling );
    }
    return div.innerHTML;
}

Call it as

html_substr( str,13, 2 );

Upvotes: 6

Related Questions