Castaldi
Castaldi

Reputation: 701

Adding missing html tags

Is it possible to add missing html tags in ASP MVC. 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.

Is there a method in ASP MVC to do this automatically or a C# function to correct them?

Upvotes: 1

Views: 2140

Answers (2)

Mouhong Lin
Mouhong Lin

Reputation: 4509

Check this gist: 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

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>       |
+-------------------------+--------------------------------+

Upvotes: 5

James Fleming
James Fleming

Reputation: 2589

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.

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

Upvotes: 0

Related Questions