I am trying to build a code formatting tool. My script gets the whole body text from the server and isolates the code block. I have the code and I am trying to check if there is a semicolon symbol in the body of the text and insert a line break after that character but the problem seems to be that HTML recognizes the <br>
tag so it breaks any line. I have also tried to use a StringBuilder to append that tag after the semicolon character but it’s not working. Below is my code
@if(code != string.Empty){
//create a new instance of StringBuilder
var str = new StringBuilder();
//find where there is a semicolon
foreach(var c in code){
str.Append(c);
if(c==';'){
//append a line break
str.Append("<br>");
}
}
//display the code in the code div
<p style="text-align:justify;">@str</p>
}
I also tried this
str.AppendLine();
which works when you write to the console but the HTML does not recognize ‘n’ as a new line character, it does recognize <br>
instead, how do I make this work?
2
Answers
When you generate the HTML dynamically, as in your case, you need to use the
Html.Raw()
method to render the HTML tags correctly.You don’t need to do all this. You can simply use the Replace method. It will replace all the occurrences of semicolon with the required string.
Just another option – why not use .AppendLine() after a semi-colon and wrap the code in <pre> tags?