从文本中去除标签(在 React JS 中) [英] Strip tag from text (in React JS)

查看:97
本文介绍了从文本中去除标签(在 React JS 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在变量 cleanHTML 中有多个完整的 html 代码,我需要从文本中去除特定标签.

I have multiple whole html code in variable cleanHTML and i need to strip specific tags from text.

let cleanHTML = document.documentElement.outerHTML

这个:

<span class="remove-me">please</span>
<span class="remove-me">me too</span>
<span class="remove-me">and me</span>

为此:

please
me too
and me

我正在尝试这样做:

var list = cleanHTML.getElementsByClassName("remove-me");
var i;
for (i = 0; i < list.length; i++) {
  list[i] = list[i].innerHTML;
}

但是我从 React 中得到错误 cleanHTML.getElementsByClassName is not a function

But i´m getting error from React cleanHTML.getElementsByClassName is not a function

知道如何以 React 喜欢的方式来做吗?

Any idea how to do it in a way React likes?

推荐答案

我从您的规范中猜测您的 cleanHTML 是一个字符串,因此您需要将该字符串转换为一个节点(例如: 通过从它创建一个 div),然后适当地解析节点.

I am guessing from your specification that your cleanHTML is a string, so you would need to convert the string to a node (eg: by creating a div from it), and then parsing the nodes appropriately.

请注意,您确实需要请求 textContent 而不是innerHTML,因为您不希望在您的反应输出中包含任何 html

Please note that you really need to request the textContent and not the innerHTML, as you do not want to have any html in your react output

const htmlContent = `<span class="remove-me">please</span>
<span class="remove-me">me too</span>
<span class="remove-me">and me</span>`;

const getNodesToRemoveFromElement = (stringContent) => {
  const el = document.createElement('div');
  el.innerHTML = stringContent;
  return el.getElementsByClassName('remove-me');
};

for (let node of getNodesToRemoveFromElement( htmlContent ) ) {
  console.log( node.textContent );
}

这篇关于从文本中去除标签(在 React JS 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆