首页 > 解决方案 > 从 innerHtml 中删除特定标签并将其呈现在反应页面上

问题描述

我使用 react 和 redux 创建了一个博客 Web 应用程序,在我的博客中有 4 个字段 id、title、seoName 和 description,并且在描述中输入我正在使用微型 Mce 文本编辑器现在我想显示保存在博客的描述字段中的文本HTML 中的类并使用椭圆截断它 在此处输入图像描述

这是存储在数据库中

    {
        "_id" : ObjectId("60640e75f7bafb14f6563d52"),
        "title" : "Improve Your Developer Experience With Nuxt Components",
        "seoName" : "improve-your-developer-experience-with-nuxt-components",
        "description" : "<p><img src=\"https://webconnect-upload.s3.amazonaws.com/160x00u0xj1ny179o3a1fd07kl26/screenshot-from-2021-03-31-11-22-39.png\" alt=\"\" width=\"802\" height=\"274\" /></p>\n<h2 id=\"introduction\">Introduction</h2>\n<p>The Nuxt team has introduced&nbsp;<strong><a href=\"https://www.npmjs.com/package/@nuxt/components\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">@nuxt/components</a></strong>&nbsp;module with the purpose to make Nuxt development faster and to make you, as a developer, more productive. This module comes with amazing features and options that will improve your development experience with Nuxt. No matter if you&rsquo;re just starting out or an advanced user,&nbsp;<a href=\"https://github.com/nuxt/components\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">@nuxt/components</a>&nbsp;provides a range of options from the simplest setup to advance configurations that will certainly benefit your projects.</p>\n<p>In a nutshell, this module automatically scans, imports and registers Vue components found in the&nbsp;<strong><code>~/components</code></strong>&nbsp;directory, so that we don't have to write import statements when we use them in either pages, layouts or even within components.</p>\n<p>&nbsp;</p>\n<blockquote>\n<p><em>This module parses your template and automatically includes the component in the file where you are using it such as a page, layout or even a component. Because Nuxt.js uses automatic code splitting to split your pages by default this module works perfect as it will only contain the components that are used on that page. Also, if you use a component in more than 2 pages, Nuxt.js will automatically create a shared chunk for them thanks to the magic of WebPack.</em></p>\n</blockquote>",
}

我只想显示截断的文本(从描述中删除图像)和其余的东西,点击阅读更多。

现在我正在使用建议是否有任何其他有效的方法

                  <p className="m-0px truncateBlogDesc"
                  dangerouslySetInnerHTML={{ __html: e.description }}
                  ></p>

标签: javascriptreactjsinnerhtmldangerouslysetinnerhtml

解决方案


您可以使用正则表达式替换字符串 ( e.description) 中的每个 <img ..> 标记。

例如 :

var tmp = inner.replace(/<img .*?>/g,"<text>"); # remove <text> to replace the tag with an empty string ​

你能试试:

​&lt;p className="m-0px truncateBlogDesc" ​dangerouslySetInnerHTML={{ __html: e.description.replace(/<img .*?>/g,"") }} ​&gt;</p>

推荐阅读