【问题标题】:JavaScript Removing text between < and >JavaScript 删除 < 和 > 之间的文本
【发布时间】:2017-01-26 15:40:00
【问题描述】:

这是我的示例字符串...

<span>&nbsp;</span><span class="citation_text" id="_148511159">Rawls, Wilson.&nbsp;
<i>Where the Red Fern Grows: The Story of Two Dogs and a Boy</i>. Garden City, NY: Doubleday, 1961. Print.</span>

我想删除 &lt;&gt; 中的所有文本,但保留 &lt;i&gt;&lt;/i&gt; 中的文本。 我得到的最接近的是这段代码

string.replace(/<.[^i]+?>/g,"")

但是它返回这个

&nbsp;<span class="citation_text" id="_148511159">Rawls, Wilson.&nbsp;
<i>Where the Red Fern Grows: The Story of Two Dogs and a Boy</i>. Garden City, NY: Doubleday, 1961. Print.

如何让它删除保存在 &lt;&gt; 中的最终跨度?

谢谢!

更新:这就是我想要的输出。

&nbsp;Rawls, Wilson.&nbsp; <i>Where the Red Fern Grows: 
The Story of Two Dogs and a Boy</i>. Garden City, NY: Doubleday, 1961. Print.

【问题讨论】:

  • 您能否显示您发布的示例字符串应该产生的确切预期输出?
  • 您可以编写几行 jQuery 到您的 span 的 unwrap()contents(),而不是针对复杂的正则表达式。只是说。
  • 你为什么要这样做?
  • @DavidThomas :谢谢,我刚刚将其添加到帖子中! Oriol:我首先将 innerHTML 内容作为字符串获取。

标签: javascript regex string replace


【解决方案1】:

注意:正如其他人所说,您不应该使用正则表达式来解析 HTML。
但如果你真的想要一个正则表达式,这里有一个删除除&lt;i&gt; 之外的标签。

正则表达式

/<\/?(?!i>)\w+.*?>/g

此表达式将匹配开始和结束标记。

您可以查看下面的示例或this demo

示例

var str = '<span>&nbsp;</span><span class="citation_text" id="_148511159">Rawls, Wilson.&nbsp; <i>Where the Red Fern Grows: The Story of Two Dogs and a Boy</i>. Garden City, NY: Doubleday, 1961. Print.</span>';

var result = str.replace(/<\/?(?!i>)\w+.*?>/g, '');

console.log(result);

说明

  • &lt;\/? 匹配标签开始和可能的斜线(用于结束标签)。
  • 如果后面的字符是 i&gt;(?!i&gt;) 会阻止匹配。
    它将排除 &lt;i&gt;&lt;/i&gt; 标记。
  • \w+ 代表标签名称(例如span)。
  • .*?&gt; 用于关闭标签之前标签名称后面的任何字符(或没有)。

【讨论】:

  • 感谢我一直在寻找的东西!
猜你喜欢
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
相关资源
最近更新 更多