【问题标题】:remove HTML from a string (in JSON response)从字符串中删除 HTML(在 JSON 响应中)
【发布时间】:2012-07-31 20:26:33
【问题描述】:
var json = {
    "Item": {
        "Items": {
         "Body": "<SPAN style=\"LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; FONT-SIZE: 11pt; mso-fareast-font-family: Calibri; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">\"We have all been inoculated with Christianity, and are never likely to take it seriously now! You put some of the virus of some dreadful illness into a man's arm, and there is a little itchiness, some scratchiness, a slight discomfort, disagreeable, no doubt, but not the fever of the real disease, the turning and the tossing, and the ebbing strength. And we have all been inoculated with Christianity, more or less. We are on Christ's side, we wish him well, we hope that He will win, and we are even prepared to do something for Him, provided, of course, that He is reasonable, and does not make too much of an upset among our cozy comforts and our customary ways. But there is not the passion of zeal, and the burning enthusiasm, and the eagerness of self-sacrifice, of the real faith that changes character and wins the world.\"<B>A.J. Gossip<\/B><\/SPAN>",
        },

    }
};
var someString = json.Item.Body.replace(/<br\s*\/?\s*>/g,"\n");   
alert(someString);
​

我在回复中收到HTML 标签,我应该删除或解析它。我该怎么办呢。我为BR标签做了,但现在似乎还有其他标签进来了。

【问题讨论】:

  • 如果您只是想“在 DOM 中添加标记”,那么 jQuery(或直接的 innerHTML 技巧)应该可以工作 -- 请记住可能的 注入攻击 用于非受控来源。如果您想获取 HTML 并将其转换为其他内容.. 那么,您有什么(以及为什么)以及您想要什么? :)
  • 现在,你想要什么 - 解析还是删除?或解析以删除它们?您需要结果的地方和用途?

标签: javascript


【解决方案1】:

我认为您只需要一个简单的正则表达式即可从内容中去除 html 样式标签。试试这个。

str.replace(/<\/?[^>]+>/gi, '')

【讨论】:

  • i 是多余的,对吧?没什么大不了的,但是很多支票上的额外“检查大小写”会加起来
【解决方案2】:

这应该会变魔术http://jsfiddle.net/Ygfvp/ 无论如何它不会剥离 html cmets

【讨论】:

  • Segu 会的。 /&lt;\/?[^&gt;]+&gt;/gi(带有转义的斜线)
【解决方案3】:

如果您使用 React 映射 Json,那么您可以留下 html 标签并使用它们。

代替:

<div>{el.content.rendered}</div>

这样做:

<div dangerouslySetInnerHTML={{__html: el.content.rendered}}></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多