Saturday, 15 March 2014

Splitting a string with JavaScript but ignoring the HTML characters in it -



Splitting a string with JavaScript but ignoring the HTML characters in it -

i'm been scratching head on 1 while , hoping there's solution out there somewhere..

i have html strings similar this:

'<a href="link.com">lorem ipsum</a> dolor sit down amet, consectetur adipiscing elit. ut lobortis luctus leo, non porta nisi euismod ut. <a href="anotherlink.com">nulla tristique</a> scelerisque fringilla.'

i need utilize javascript truncate/split text after number of characters, not counting html in links, still rendering links in resulting text. example, if i'm truncating @ 20 characters i'd want next displayed, 'lorem ipsum' text still linked:

lorem ipsum dolor si

if utilize str.substring(0,20) html characters in string displayed get:

<a href="link.com">l

which renders hyper-linked l:

l

does have suggestions me? tried doing search couldn't find appropriate answer.

if helps have both raw non-html text , total html text (with links) available can utilize in js. don't want utilize raw text though won't render of links. example, if split text @ 200 characters i'd want of links still rendered in html, 200 characters of actual on-screen text displayed user.

hopefully makes sense. many in advance help!

john

edit: clarify i'm trying accomplish;

i have post (text string) has links in it. want count characters of text excluding html characters in links. want truncate text still include html links, show x number of characters user.

for example;

'<a href="link.com">lorem ipsum</a> dolor sit down amet, consectetur adipiscing elit. ut lobortis luctus leo, non porta nisi euismod ut. <a href="anotherlink.com">nulla tristique</a> scelerisque fringilla.'

when truncated 40 characters displayed as:

'<a href="link.com">lorem ipsum</a> dolor sit down amet, consectetur adi'

so includes links shows 40 characters of text user. if utilize str.substring(0,40) includes links in character count , ends showing:

'<a href="link.com">lorem ipsum</a> dolo'

hopefully makes sense. apologies confusion.

you can utilize this:

var s = '<a href="link.com">lorem ipsum</a> dolor sit down amet, consectetur adipiscing elit. ut lobortis luctus leo, non porta nisi euismod ut. <a href="anotherlink.com">nulla tristique</a> scelerisque fringilla.' var div = document.createelement("div"); div.innerhtml = s; var text = div.textcontent || div.innertext; var substr = text.substring(0, 20); //=> "lorem ipsum dolor si"

javascript html regex string substring

No comments:

Post a Comment