简体   繁体   中英

How can I check if my string starts with <p> and add that text if it doesn't in C#

If I have string named codeText. Sometimes that string starts with a <p> and other times not. Can anyone tell me how I can check if it starts with <p> and if it doesn't then how can I add the <p> to the start and </p> to the end.

if(!text.StartsWith("<p>"))
{
    text = string.Format("<p>{0}</p>", text);
}

Like this:

if (!text.StartsWith("<p>", StringComparison.OrdinalIgnoreCase))
    text = "<p>" + HttpUtility.HtmlEncode(text) + "</p>";

If you somehow know that the HTML string does not contain any malicious Javascript, you don't want to call HtmlEncode .

You mean like this?

if (!codeText.StartsWith("<p>"))
{
    codeText = string.Concat("<p>", codeText, "</p>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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