Html - insert html into <p> </p> tags
Let's say I have a text :
<p> hello world! </p>
and I am using a function that cut the text after 5 words and adds " ...show more"
I want the result to be like this :
hello ... show more
Because of the <p>
tags what I get is this output :
hello ...show more
what I see when I inspect the element is this :
<p> hello </p> ...show more
I must mention that the text can be with <p>
or without.
Is there a way to solve this problem ?
Is there a way to insert the added text inside the <p>
tag ?
I need to mention that I need the <p>
tags, I can开发者_Python百科't use strip tags function.
Thanks, Yami
Do you mean this?
var text = "<p>hello world</p>";
var res = "<p>" + text.substring(3, 8) + " ...show more</p>";
It results in:
<p>hello ...show more</p>
The way I see it, you have two options:
.split()
the string by spaces (assuming a space separates words) then slice the first (up to) 5 elements. If there are greater than 5 element, add "...read more"; if not, it's unnecessary.- You can use some regex replace and (with a negative lookahead) ignore the first 5 words, but replace all other text with your "...read more". (I personally find this one having more overhead, but you could probably use
(?!(?:[^\b]+?[\b\s]+?){5})(.*)$
as a pattern)
Having said that, here's what i mean with a string split:
function readMore(el){
var ary = el.innerHTML.split(' ');
el.innerHTML = (ary.length > 5 ? ary.slice(0,5).join(' ') + '... read more' : ary.join(' '));
}
var p = document.getElementById('foo');
readMore(p);
Assuming of course, for the purposes of this demo, <p id="foo">Hello, world! How are you today?</p>
(which would result in <p id="foo">Hello, world! How are you...read more</p>
)
$('p').text($('p').text().replace('world!', '... show more'));
精彩评论