简体   繁体   English

如何检查我的字符串是否以 <p> 并添加该文本(如果不在C#中)

[英]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. 如果我有一个名为codeText的字符串。 Sometimes that string starts with a <p> and other times not. 有时,该字符串以<p>开头,而其他时候则不是。 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. 谁能告诉我如何检查它是否以<p>开头,如果不是,那么如何将<p>添加到开头并将</p>到结尾。

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 . 如果您以某种方式知道HTML字符串不包含任何恶意Javascript,则不要调用HtmlEncode

You mean like this? 你的意思是这样吗?

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

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

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