从字符串中删除脚本和链接标签

时间:2019-06-11 09:52:07

标签: c# html string

我正在尝试从字符串中删除scriptlink标签。下面是我到目前为止所得到的。

代码

rawHtml = rawHtml.Remove(rawHtml.IndexOf("<script"), (rawHtml.LastIndexOf("</script>") - 
          rawHtml.IndexOf("<script")) + 5);

rawHtml = rawHtml.Remove(rawHtml.IndexOf("<link"), (rawHtml.LastIndexOf("/>") - 
          rawHtml.IndexOf("<link")) + 3);

是否有更好的方法而无需手动输入数字?

2 个答案:

答案 0 :(得分:2)

这将删除脚本,链接和样式标签之间的所有内容,然后从其余部分中删除html标签(但保留内容)。

注意:在对我以前的回答进行@yelliver改进后,已将其合并(已投票)并解决了您关于链接的观点。

/// <summary>
/// Helper method to strip html tags from html
/// </summary>
/// <param name="htmlText">raw html</param>
/// <returns>string without html tags</returns>
public string StripHTML(string hTMLText)
{
    // Remove script and style tags
    Regex rRemScript = new Regex(@"<(script|style)[^>]*>[\s\S]*?</\1>");
    hTMLText = rRemScript.Replace(hTMLText, "");

    // Remove link tags AND CONTENTS
    Regex rRemLink = new Regex(@"<link[\s\S]*?/>");
    hTMLText = rRemLink.Replace(hTMLText, "");

    // Strip other html tags (leaving contents)
    Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
    return reg.Replace(hTMLText, "");
}

答案 1 :(得分:2)

使用反向引用,我可以改善@HockeyJ答案: 代替:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function Home() {
  return (
    <div className="Home" style={{overflow: window.innerWidth >= 1024 ? 'hidden' : 'initial'}}>
      <h1>Home </h1>
    </div>
  );
}

function Page() {
  return (
    <div className="Page" style={{overflow: 'initial'}}>
      <h1>Page</h1>
    </div>
  );
}

只需使用:

Regex rRemScript = new Regex(@"<script[^>]*>[\s\S]*?</script>");
hTMLText = rRemScript.Replace(hTMLText, "");

// Remove link content
Regex rRemLink = new Regex(@"<link[^>]*>[\s\S]*?</link>");
hTMLText = rRemLink.Replace(hTMLText, "");

// Remove style content
Regex rRemStyle = new Regex(@"<style[^>]*>[\s\S]*?</style>");
hTMLText = rRemStyle.Replace(hTMLText, "");
相关问题