简体   繁体   English

添加缺少的html标签

[英]Adding missing html tags

Is it possible to add missing html tags in ASP MVC. 是否可以在ASP MVC中添加缺少的html标签。 Here is what I mean: 这是我的意思:

String x = "<p><b>Hello world how are you</b></p>";

Substing of that string at the first few character would result in: 将该字符串替换为前几个字符将导致:

String x = "<p>Hello world ";

Where there is the </p> tag missing, using @MvcHtmlString.Create(x) in a loop will cause a confusion of tags cause of the missing tags. 缺少</p>标记的地方,在循环中使用@MvcHtmlString.Create(x)会导致标记混乱,从而导致标记丢失。

Is there a method in ASP MVC to do this automatically or a C# function to correct them? ASP MVC中是否有一种方法可以自动执行此操作,还是可以使用C#函数对其进行更正?

Check this gist: https://gist.github.com/mouhong/c09487502e261f7ce53d 检查要点: https : //gist.github.com/mouhong/c09487502e261f7ce53d

It will close missing end tags (supports nested tags) and broken end tags, and will ignore broken start tags. 它将关闭缺少的结束标签(支持嵌套标签)和损坏的结束标签,并忽略损坏的开始标签。

It's not fully tested, let me know if you find any bug :P 它没有经过全面测试,如果发现任何错误,请告诉我:P

Usage: 用法:

"<p>Hello".CloseTags();

Examples: 例子:

+-------------------------+--------------------------------+
|            Input        |          Output                |
+-------------------------+--------------------------------+
| <div>Hello World        | <div>Hello World</div>         |
| <div>Hello, <b>World    | <div>Hello, <b>World</b></div> |
| <div>Hello World</di    | <div>Hello World</div>         |
| <div>Hello, <b>World</  | <div>Hello, <b>World</b></div> |
| <div>Hello World. <span | <div>Hello World. </div>       |
+-------------------------+--------------------------------+

1probably the easiest thing to do would create a helper function that takes in the output from MvcHtmlString.Create(x) and adds the closing tag if missing. 1可能最简单的方法是创建一个辅助函数,该辅助函数接收MvcHtmlString.Create(x)的输出并在缺少时添加结束标记。

It would look something like this (not tested) 看起来像这样(未经测试)

    private string CloseTag(string snippet)
    {
        if (string.IsNullOrEmpty(snippet) || (snippet.TrimStart().StartsWith("<") && snippet.TrimEnd().EndsWith(">")) || !snippet.TrimStart().StartsWith("<"))
        {
            return snippet;
        }

        var index = snippet.IndexOf('>');
        var tag = snippet.Substring(1, index - 1);
        return snippet.TrimEnd() + "</" + tag + ">";
    }

with a bit of clean up, you could create an extension method and invoke this on your strings directly 经过一点清理,您可以创建一个扩展方法并直接在字符串上调用此方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM