I'm been scratching my head on this one for a while now and am hoping there's a solution out there somewhere..
I have some HTML strings similar to this:
'<a href="link.com">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. Ut lobortis luctus leo, non porta nisi euismod ut. <a href="anotherlink.com">Nulla tristique</a> scelerisque fringilla.'
I need to use JavaScript to truncate/split the text after a certain number of characters, not counting the HTML in the links, but still rendering the links in the resulting text. So for example, if I'm truncating it at 20 characters then I'd want the following to be displayed, but with the 'Lorem ipsum' text still linked:
Lorem ipsum dolor si
If I just use str.substring(0,20) then the HTML characters in the string are also displayed so I get:
<a href="link.com">L
Which just renders as a hyper-linked L:
L
Does anyone have any suggestions for me? I tried doing a search but couldn't find an appropriate answer.
If it helps I have both the raw non-HTML text and the full HTML text (with links) available that I can use in the JS. I don't want to just use the raw text though as it then won't render any of the links. For example, if I split the text at 200 characters then I'd want all of the links to still be rendered in the HTML, but for only 200 characters of actual on-screen text to be displayed to the user.
Hopefully that makes sense. Many thanks in advance for any help!
John
EDIT: To clarify what I'm trying to accomplish;
I have a post (text string) which has links in it. I want to count the characters of the text excluding the HTML characters in the links. I then want to truncate the text to still include the HTML links, but only show X number of characters to the user.
For example;
'<a href="link.com">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit. Ut lobortis luctus leo, non porta nisi euismod ut. <a href="anotherlink.com">Nulla tristique</a> scelerisque fringilla.'
When truncated to 40 characters would be displayed as:
'<a href="link.com">Lorem ipsum</a> dolor sit amet, consectetur adi'
So it includes the links but only shows 40 characters of text to the user. If I use str.substring(0,40) then it includes the links in the character count and ends up showing:
'<a href="link.com">Lorem ipsum</a> dolo'
Hopefully that makes sense. Apologies for the confusion.