Ad

Javascript Substring With Html Tags

- 1 answer

I have searched too much on same topic but not is perfect for what I am looking for.

I have a string like :

var string ='<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>'

Now what I want is to substring it with limit with javascript substring function but don't want tags to be cut in middle like for example

<strong><span>Hii </span> <p

It should be like

<strong><span>Hii </span> <p>

I am using

string.substr(0,200)

string is dynamic variable with html tags

Ad

Answer

Its not elegant but it works, will increase the characters to include the next closing tag https://jsfiddle.net/q680vors/

Just change length to the required number of characters.

var string ='<strong><span>Hii </span> <p>this is just a demo <span>string<span></p></strong>';

var length = 2;
var openTag = 0, closeTag = 0,i=0;
for(i; i<length; i++)
{
    if(string[i] == "<")
        openTag++;
    if(string[i] == ">")
        closeTag++;
}
if(openTag > closeTag)
{
    while(string[i] != ">")
        i++;
}

var newString = string.substring(0,(i+1));

alert(newString);
Ad
source: stackoverflow.com
Ad