HTML text don't rendering as in code lines [duplicate] - html

I have an MVC3 app that has a details page. As part of that I have a description (retrieved from a db) that has spaces and new lines. When it is rendered the new lines and spaces are ignored by the html. I would like to encode those spaces and new lines so that they aren't ignored.
How do you do that?
I tried HTML.Encode but it ended up displaying the encoding (and not even on the spaces and new lines but on some other special characters)

Just style the content with white-space: pre-wrap;.
div {
white-space: pre-wrap;
}
<div>
This is some text with some extra spacing and a
few newlines along with some trailing spaces
and five leading spaces thrown in
for good
measure
</div>

have you tried using <pre> tag.
<pre>
Text with
multipel line breaks embeded between pre tag
will work and
also tabs..will work
it will preserve the formatting..
</pre>

You can use white-space: pre-line to preserve line breaks in formatting. There is no need to manually insert html elements.
.popover {
white-space: pre-line;
}
or add to your html element style="white-space: pre-line;"

You would want to replace all spaces with (non-breaking space) and all new lines \n with <br> (line break in html). This should achieve the result you're looking for.
body = body.replace(' ', ' ').replace('\n', '<br>');
Something of that nature.

I was trying the white-space: pre-wrap; technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre> tags and the following css and everything was good to go..
pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}

As you mentioned on #Developer 's answer, I would probably HTML-encode on user input. If you are worried about XSS, you probably never need the user's input in it's original form, so you might as well escape it (and replace spaces and newlines while you are at it).
Note that escaping on input means you should either use #Html.Raw or create an MvcHtmlString to render that particular input.
You can also try
System.Security.SecurityElement.Escape(userInput)
but I think it won't escape spaces either. So in that case, I suggest just do a .NET
System.Security.SecurityElement.Escape(userInput).Replace(" ", " ").Replace("\n", "<br>")
on user input.
And if you want to dig deeper into usability, perhaps you can do an XML parse of the user's input (or play with regular expressions) to only allow a predefined set of tags.
For instance, allow
<p>, <span>, <strong>
... but don't allow
<script> or <iframe>

There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"];
echo nl2br($text);

Related

In HTML text don't break at the existing hyphen in the text [duplicate]

We have the CKEditor in our CMS. Our end users will input some long articles via that CKEditor. We need a way to prevent line break at hyphens on those articles.
Is there a way to prevent line break at hyphens in all browsers?
Or does CKEditor have an option to prevent that?
You can use ‑ which is a Unicode NON-BREAKING HYPHEN (U+2011).
HTML: ‑ or ‑
Also see: http://en.wikipedia.org/wiki/Hyphen#In_computing
One solution could be to use an extra span tag and the white-space CSS property. Just define a class like this:
.nowrap {
white-space: nowrap;
}
And then add a span with that class around your hyphenated text.
<p>This is the <span class="nowrap">anti-inflammable</span> model</p>
This approach should work just fine in all browsers - the buggy implementations listed here are for other values of the white-space property: http://reference.sitepoint.com/css/white-space#compatibilitysection
I’m afraid there’s no simpler way to do it reliably than splitting the text to “words” (sequences of non-whitespace characters separated by whitespace) and wrapping each “word” that contains a hyphen inside nobr markup. So input data like bla bla foo-bar bla bla would be turned to bla bla <nobr>foo-bar</nobr> bla bla.
You might even consider inserting nobr markup whenever the “word” contains anything but letters and digits. The reason is that some browsers may even break strings like “2/3” or “f(0)” (see my page on oddities of line breaking in browsers).
You are unable to do it without editing every HTML instance. Consequently, I wrote some JavaScript code to replace them:
jQuery:
// Replace hyphens with non-breaking ones
$txt = $("#block-views-video-block h2");
$txt.text( $txt.text().replace(/-/g, '‑') );
Vanilla JavaScript:
function nonBrHypens(id) {
var str = document.getElementById(id).innerHTML;
var txt = str.replace(/-/g, '‑');
document.getElementById(id).innerHTML = txt;
}
Use the word joiner character (⁠) around the hyphen. It works in Internet Explorer as well.
Fix specific hyphens...
function fixicecream(text) {
return text.replace(/ice-cream/g, 'ice⁠-⁠cream'));
}
Or everything...
function fixhyphens(text) {
return text.replace(/(\S+)-(\S+)/g, '$1⁠-⁠$2'));
}
Try this CSS:
word-break: break-all;
-webkit-hyphens:none;
-moz-hyphens: none;
hyphens: none;

Rendering newlines in escaped html

We have a display message that is auto-generated by default, but may be overridden by GET vars from the url. Since we need to treat the message as user input, it must be escaped for display. However, we want to retain the ability to include newlines.
Newlines as <br>
This won't work because escaping HTML destroys the <br> tag.
Newlines as \n
I can't figure out how to get \n to render as newlines. I thought putting it in a tag would render correctly, but no luck: http://jsfiddle.net/7L932/
Escape the HTML, and then replace \n with <br>.
In case you want to use \n, I fix your fiddle for you http://jsfiddle.net/hr3bg/
Setting wrapper html css to white-space: pre-line did the trick for me. It enables \n character's new line feature
What you're doing is more or less fine, except for you should put \n character (newline), not the escape sequence in your html (and what Prinzhorn says also makes perfect sense, so I'll go upvote him).
Your theory's sound, but \n is a not an HTML-recognised way of inserting a new line. It either comes in explicitly (as I've inserted in a new .linebreaks element) as a literal return in the markup, or, if you're using some intermediary scripting language that does recognise \n (like JS), do that (as I've done to your first .linebreaks with the jQuery code I inserted.
See my tweak to your example: http://jsfiddle.net/barney/7L932/2/

Render a string in HTML and preserve spaces and linebreaks

I have an MVC3 app that has a details page. As part of that I have a description (retrieved from a db) that has spaces and new lines. When it is rendered the new lines and spaces are ignored by the html. I would like to encode those spaces and new lines so that they aren't ignored.
How do you do that?
I tried HTML.Encode but it ended up displaying the encoding (and not even on the spaces and new lines but on some other special characters)
Just style the content with white-space: pre-wrap;.
div {
white-space: pre-wrap;
}
<div>
This is some text with some extra spacing and a
few newlines along with some trailing spaces
and five leading spaces thrown in
for good
measure
</div>
have you tried using <pre> tag.
<pre>
Text with
multipel line breaks embeded between pre tag
will work and
also tabs..will work
it will preserve the formatting..
</pre>
You can use white-space: pre-line to preserve line breaks in formatting. There is no need to manually insert html elements.
.popover {
white-space: pre-line;
}
or add to your html element style="white-space: pre-line;"
You would want to replace all spaces with (non-breaking space) and all new lines \n with <br> (line break in html). This should achieve the result you're looking for.
body = body.replace(' ', ' ').replace('\n', '<br>');
Something of that nature.
I was trying the white-space: pre-wrap; technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre> tags and the following css and everything was good to go..
pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}
As you mentioned on #Developer 's answer, I would probably HTML-encode on user input. If you are worried about XSS, you probably never need the user's input in it's original form, so you might as well escape it (and replace spaces and newlines while you are at it).
Note that escaping on input means you should either use #Html.Raw or create an MvcHtmlString to render that particular input.
You can also try
System.Security.SecurityElement.Escape(userInput)
but I think it won't escape spaces either. So in that case, I suggest just do a .NET
System.Security.SecurityElement.Escape(userInput).Replace(" ", " ").Replace("\n", "<br>")
on user input.
And if you want to dig deeper into usability, perhaps you can do an XML parse of the user's input (or play with regular expressions) to only allow a predefined set of tags.
For instance, allow
<p>, <span>, <strong>
... but don't allow
<script> or <iframe>
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"];
echo nl2br($text);

How to prevent line break at hyphens in all browsers

We have the CKEditor in our CMS. Our end users will input some long articles via that CKEditor. We need a way to prevent line break at hyphens on those articles.
Is there a way to prevent line break at hyphens in all browsers?
Or does CKEditor have an option to prevent that?
You can use ‑ which is a Unicode NON-BREAKING HYPHEN (U+2011).
HTML: ‑ or ‑
Also see: http://en.wikipedia.org/wiki/Hyphen#In_computing
One solution could be to use an extra span tag and the white-space CSS property. Just define a class like this:
.nowrap {
white-space: nowrap;
}
And then add a span with that class around your hyphenated text.
<p>This is the <span class="nowrap">anti-inflammable</span> model</p>
This approach should work just fine in all browsers - the buggy implementations listed here are for other values of the white-space property: http://reference.sitepoint.com/css/white-space#compatibilitysection
I’m afraid there’s no simpler way to do it reliably than splitting the text to “words” (sequences of non-whitespace characters separated by whitespace) and wrapping each “word” that contains a hyphen inside nobr markup. So input data like bla bla foo-bar bla bla would be turned to bla bla <nobr>foo-bar</nobr> bla bla.
You might even consider inserting nobr markup whenever the “word” contains anything but letters and digits. The reason is that some browsers may even break strings like “2/3” or “f(0)” (see my page on oddities of line breaking in browsers).
You are unable to do it without editing every HTML instance. Consequently, I wrote some JavaScript code to replace them:
jQuery:
// Replace hyphens with non-breaking ones
$txt = $("#block-views-video-block h2");
$txt.text( $txt.text().replace(/-/g, '‑') );
Vanilla JavaScript:
function nonBrHypens(id) {
var str = document.getElementById(id).innerHTML;
var txt = str.replace(/-/g, '‑');
document.getElementById(id).innerHTML = txt;
}
Use the word joiner character (⁠) around the hyphen. It works in Internet Explorer as well.
Fix specific hyphens...
function fixicecream(text) {
return text.replace(/ice-cream/g, 'ice⁠-⁠cream'));
}
Or everything...
function fixhyphens(text) {
return text.replace(/(\S+)-(\S+)/g, '$1⁠-⁠$2'));
}
Try this CSS:
word-break: break-all;
-webkit-hyphens:none;
-moz-hyphens: none;
hyphens: none;

How to save user-entered line breaks from a TextArea to a database?

How do I save user-entered line breaks from a <textarea> HTML element to a database?
It always removes the line breaks.
TextArea HTML element is preserving the white space in the database.
The problem appears when trying to display the \n on the web browser, which will fail.
To display \n in the web browser use :
<p style="white-space: pre-line">multi-line text</p>
When displaying the content you need to convert line breaks into <br /> tags, otherwise the web browser won't display them. This is probably why you think they aren't being saved. If you're using PHP, use the nl2br() function to do this. In other languages you could do a string replace, replacing all occurrences of "\n" with "<br />".
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
I just learnt to use php's nl2br function and it is working fine for me.
I'm using it to style how my users receive an email when sent from another user.
Your problem will be solved using 'white-space' property: simply use:
<textarea name="description" id="description" style="white-space: pre-wrap;"></textarea>
And continue your work.
I know from experience that Browser text areas are less well-behaved than one would like, especially with regard to line breaks.
You could can to see if javascript would be able to interrogate the text area and find the line breaks before the text is sent to the server and so send the data in a more well-formatted way. But the amount of javascript debugging necessary to make this work across multiple browsers is probably not worth the effort.
Perhaps you should say that format you are trying to capture your data. There may be a better way to get the data than keeping track of line-breaks - though lines breaks can seem like any easy thing to capture in user input.
I noticed that breakable content saved normally if textarea is inside a html form. But if I use textarea without any form and try to edit a long text in it, insert line breaks and save content via ajax, it's saved as a merged text into database
Use PHP nl2br() Function while saving data from textarea to database
like below
<textarea
name="PostContent"
class="form-control"
rows="12" cols="30"
id="PostContent"
required=""
style="white-space: pre-wrap; text-indent: 50px;"
>
</textarea>
$PostContent=$_POST["PostContent"];
$output =nl2br($PostContent);
use $output variable to save to Database
you can add text in the text area and see the formatted text below.
function ex() {
const text = document.getElementById("description").value;
const ss = document.getElementById("add");
ss.textContent = text;
}
<textarea name="description" id="description" style="white-space: pre-wrap;"></textarea>
</br>
<button onclick="ex();">check</button>
</br>
<p style="white-space: pre-line" id="add"></p>
<style>
p {
color: red;
text-align: center;
}
</style>