How to prevent line break at hyphens in all browsers - html

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;

Related

Non-breaking en dash, not a hyphen

I know in html there is a non-breaking hyphen (#8209), but I am needing a non-breaking en dash (#8211). They are used differently. Is there proper way of doing this besides wrapping the text and en-dash with no-break code throughout my document, like:
<nobr> TEXT #8211 TEXT </nobr>
Try surrounding the en dash with the Word-Joiner character (#8288).
TEXT⁠–⁠TEXT
This question was driving me crazy in a recent project. I found it hard to believe that en dashes are by default breaking characters. If you're okay inserting extra characters with html, then ⁠ works well. Note, only a word-joiner is necessary after the en dash, since I believe they don't break before.
For a number of reasons, manually putting extra characters everywhere in my source HTML was not going to work for me, and I came up with a javascript solution which automatically applies a .nobreak CSS class to any en dash and the character immediately following it.
<style>
.nobreak {
white-space: nowrap;
}
</style>
<body>
<p>This is a paragraph with a number range, 1–34, and it will never break after the en dash.</p>
<script>
$("body").html(function(_, html) {
return html.replace(/(–.)/g, '<span class="nobreak">$1</span>')
});
</script>
</body>
An even simpler solution might be to use the same script to automatically insert ⁠ after en dashes. Just change the js to:
$("body").html(function(_, html) {
return html.replace(/–/g, '–⁠')
});
As per of this documentation, and other answer about the word joiner –, the following HTML should produce a non breakable en dash:
If the character does not have an HTML entity, you can use the decimal
(dec) or hexadecimal (hex) reference.
<p>
Will break :
<br />
TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT–TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT
<p>
<p>
Won't break (word joiner):
<br />
TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT⁠–⁠TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT
<p>

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

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);

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;

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);

Line Break in XML? [duplicate]

This question already has an answer here:
How to add a newline (line break) in XML file?
(1 answer)
Closed 4 years ago.
I'm a beginner in web development, and I'm trying to insert line breaks in my XML file.
This is what my XML looks like:
<musicpage>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
</musicpage>
I want to have line breaks in between the sentences for the lyrics. I tried everything from /n, 
 and other codes similar to it, PHP parsing, etc., and nothing works! Have been googling online for hours and can't seem to find the answer. I'm using the XML to insert data to an HTML page using Javascript.
Does anyone know how to solve this problem?
And this is the JS code I used to insert the XML data to the HTML page:
<script type="text/javascript">
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","xml/musicpage_lyrics.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
var x=xmlDoc.getElementsByTagName("songs");
for (i=0;i<x.length;i++) {
document.write("<p class='msg_head'>");
document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("</p><p class='msg_body'>");
document.write(x[i].getElementsByTagName("lyric")[0].childNodes[0].nodeValue);
document.write("</p>");
}
</script>
#icktoofay was close with the CData
<myxml>
<record>
<![CDATA[
Line 1 <br />
Line 2 <br />
Line 3 <br />
]]>
</record>
</myxml>
In XML a line break is a normal character. You can do this:
<xml>
<text>some text
with
three lines</text>
</xml>
and the contents of <text> will be
some text
with
three lines
If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.
* Note that
is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.
This is where neither
nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.
Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.
Here is a JavaScript function that inserts <br> into a multi-line string:
function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }
Alternatively you can force line breaks at new line characters with CSS:
div.lines {
white-space: pre-line;
}
just use <br> at the end of your lines.
At the end of your lines, simply add the following special character:
That special character defines the carriage-return character.
In the XML: use literal line-breaks, nothing else needed there.
The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).
Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks
.msg_body {
white-space: pre-line;
}
But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].
So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]
[get lyric...].nodeValue
.replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
.replace(/[ \t]+/g, ' ')
.replace(/ ?([\r\n]) ?/g, '$1')
and then preserve those line-breaks with
.msg_body {
white-space: pre; // for IE 6 and 7
white-space: pre-wrap; // or pre-line
}
or, instead of that CSS, add a .replace(/\r?\n/g, '<br />') after the other JavaScript .replaces.
(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>, you'd have to escape <,&(,>,",') before generating the <br>s.)
--
[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling
[2] http://www.quirksmode.org/css/whitespace.html
[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.
[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n")
<song>
<title>Song Tigle</title>
<lyrics>
<line>The is the very first line</line>
<line>Number two and I'm still feeling fine</line>
<line>Number three and a pattern begins</line>
<line>Add lines like this and everyone wins!</line>
</lyrics>
</song>
(Sung to the tune of Home on the Range)
If it was mine I'd wrap the choruses and verses in XML elements as well.
If you use CDATA, you could embed the line breaks directly into the XML I think. Example:
<song>
<title>Song Title</title>
<lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>
<description><![CDATA[first line<br/>second line<br/>]]></description>
If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.