简体   繁体   English

Html - 将html插入 <p></p> 标签

[英]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" 我正在使用一个功能,在5个单词后剪切文字并添加“...显示更多”

I want the result to be like this : 我希望结果是这样的:

hello ... show more 你好...显示更多

Because of the <p> tags what I get is this output : 由于<p>标签,我得到的是这个输出:

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. 我必须提到文本可以是<p>或不带。

Is there a way to solve this problem ? 有没有办法解决这个问题? Is there a way to insert the added text inside the <p> tag ? 有没有办法在<p>标签内插入添加的文字? I need to mention that I need the <p> tags, I can't use strip tags function. 我需要提一下,我需要<p>标签,我不能使用条带标签功能。

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. .split()字符串的空格(假设空格分隔单词)然后切片第一个(最多)5个元素。 If there are greater than 5 element, add "...read more"; 如果大于5个元素,请添加“...阅读更多”; 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". 您可以使用一些正则表达式替换和(使用否定前瞻)忽略前5个单词,但用“... read more”替换所有其他文本。 (I personally find this one having more overhead, but you could probably use (?!(?:[^\\b]+?[\\b\\s]+?){5})(.*)$ as a pattern) (我个人认为这个有更多的开销,但你可以使用(?!(?:[^\\b]+?[\\b\\s]+?){5})(.*)$作为模式)

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> 当然,假设为了本演示的目的, <p id="foo">Hello, world! How are you today?</p> <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 id="foo">Hello, world! How are you today?</p> (这将导致<p id="foo">Hello, world! How are you...read more</p>

$('p').text($('p').text().replace('world!', '... show more'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM