NewLine escape character not working - javascript

We know that \n is used to feed a new line in JavaScript.
How should I use it for an output (in a for-loop):
str=prompt("Enter any string!");
for(i=0;i<str.length;i++)
{
document.write('\n'+str.charCodeAt(i));
}
or
str=prompt("Enter any string!");
for(i=0;i<str.length;i++)
{
document.write('\n'+str.charCodeAt(i));
}
Neither seems to work.

This has nothing to do with JavaScript. In HTML, all whitespace (including newlines) is collapsed and treated as a single space.
To do a line break in HTML:
Use <br>
Or organize your text into paragraphs with <p>...</p>, etc.)
Or if you're outputting some form of formatted text (like code), you can do that in a <pre>...</pre> element (or any element with the white-space: pre, white-space: pre-wrap, or white-space: pre-line style applied to it).

If you're writing to the document you'll want document.write('<br/>'+str.charCodeAt(i));
- or to set your output in a <pre> tag (or another element with the a style attribute of white-space:pre).

I made a much better solution. See it in action https://repl.it/#mamamia5x/Example
In css do
h1 span::before {
content: "\A";
white-space: pre;
}
Replace the h1 with whatever you have. Now, whenever you do <span>, a new line will break. So whenever someone says /n, it'll do the <span> and make a new line.
if (txt.charAt(i) == '/' && txt.charAt(i + 1) =='n'){
document.getElementById("text").innerHTML += " <span>";
i = i + 2;
}
Here is it in action https://repl.it/#mamamia5x/Example, and here is a project I am using it for https://live-stream.mamamia5x.repl.co/.
I also made it work with <br>. If you want to do that, you can do
if (txt.charAt(i) == '<' && txt.charAt(i + 1) == 'b' && txt.charAt(i + 2) == 'r' && txt.charAt(i + 3) == '>'){
You can also mix the two together, and it can allow /n and <br>.

use document.writeln() method .
The writeln() method is identical to the write() method, with the addition of writing a newline character after each statement.
try this
str=prompt("Enter any string!");
for(i=0;i<str.length;i++)
{
document.writeln(str.charCodeAt(i));
}

use <br> instead of \n
it relative to HTML

Related

Stairs pattern in javascript

This function in Javascript doesn't works as desired. But when written in C, it works as desired.
var patt_2 = function()
{
for(i=5;i>=1;i--)
{
for(j=1;j<i;j++)
{
$("#panel8").append(" ");
}
for(k=5;k>=i;k--)
{
$("#panel8").append("*");
}
$("#panel8").append("<br/>");
}
};
Undesired output
Desired Output
You could give your #panel8 element the following to allow for non characters to also allow multiple whitespace:
#panel8 {
white-space: pre;
}
You can read here what this does, quote:
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.
Basically HTML collapses whitespace characters (" ") to create one space, if you use you overcome this issue but creates uglier code in general (since you'll have to append " " to your string all the time).
If your element can have white-space: pre; then this is a clean and easy solution which doesn't require you to edit your script!
P.S. It's not JS in which it's not working but rather HTML or the HTML parser that collapses the whitespace.

Javascript: Adding '<' seems to break html

I have a scenario where i have strings which have the character '<' in it. An example of this is
<a href='#'>foobar</a> foo <bar
Using the native JavaScript (innerHTML) as well as jQuery (.html()), while trying to add it to the DOM, the text after and including < gets stripped off
<a href='#'>foobar</a> foo
I tried escaping the '<' however that escapes the <a> as well. Anchors are not the only html tag that may be there, so how can i handle in such a way that i can only encode the '<' that are not part of any html entity.
An example of the problem - http://jsfiddle.net/ovbg3p8m/
Please note i get the entire HTML from somewhere else and have to work with that.
Thanks.
You can use < instead for a less than symbol.
Use <, not <. .
Try using the appropriate entry from the HTML name column here.
<
is the escaping you desire for this symbol.
The key is to escape what needs to be escaped and not the tag as that is html you want to preserve.
Let's say your build your HTML like:
var text = "foo <bar";
var link_text = "foobar";
var html = '' + link_text + '' + text;
$(".node").html(html);
If you escape just text and link_text (but not html) you're good.
The distinction between what is html and what isn't is very important.
In PHP there is the function htmlspecialchars which replaces &, ", ', < and > by their escaped forms: & " &apos; < >. This is sufficient to avoid breaking HTML.
you have to escape the <
var text = 'foobar foo <bar foobar';
Find more here
Escape html

How to convert \n to HTML line break

I am using this plugin to parse bbcode bbcodeparser
but it has no functionality to convert \n to <br/>.
I tried adding this:
replace(/\r?\n|\r/g, '<br>')
...but it didn't work.
How can I implement line break functionality?
If you are doing this to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.
<span style="white-space: pre-line">#Model.CommentText</span>
The above answer helped me to fix my problem but I dig down a little more and found some additional info about white-space properties. I hope it may help someone like me:
What is white-space property:
white-space is a CSS property that helps control how whitespace and line breaks within an element's text are treated. It can take these values: normal, nowrap, pre, pre-line, pre-wrap.
actually, Browsers doesn't treat \r\n as real new-lines, in PHP nl2br used, where as in Javascript you can use below function for nl2br() equivalent.
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');}
This worked for me
const regex = /\\n|\\r\\n|\\n\\r|\\r/g;
string.replace(regex, '<br>');

replace special characters within a block using regex

I need to replace all < and > between [code] block. I DO NOT want to select and replace all content within [code] I just want to select < and > within that and then temporary replace it to another characters. do other replacement and then back them to < > within [code].
solution that I use:
replace(/<(?=[^\[]*\[\/code\])/gi,"&_lt_;");
replace(/>(?=[^\[]*\[\/code\])/gi,"&_gt_;");
DO OTHER REPLACEMENT/CUSTOMIZATION HERE
replace(/&_lt_;/gi,"<");
replace(/&_gt_;/gi,">");
only problem is that if content between [code] contain character [ it do not work before that character in block. how can I fix this?
example that works:
<b>
[code]
<form action="nd.php" method="post">
<b>
<strong>
[/code]
<b>
example that do not works:
<b>
[code]
<form action="nd.php" method="post">
<b>
$_POST[
<strong>
[/code]
<b>
EDIT: please only provide simple regex replace solution. I can not use callback function for this issue.
The accepted-answer for the linked question doesn't work for me for the "example that works". However, the other answer does - it also works for the "example that does not work" (there was a typo though).
Try the following regex:
/(\[code\][\s\S]*?\[\/code\])|<[\s\S]*?>/g
In the replace() function, you would use:
.replace(/(\[code\][\s\S]*?\[\/code\])|<[\s\S]*?>/g, '$1');
EDIT
If I understand correctly, your end-goal is to keep all of the content within [code][/code] the same - but be able to do replacements on all HTML tags that are outside of these tags (which may or may not mean to fully strip the characters)?
If this is the case, there is no need for a long list of regexes; The above regex can be used (with a slight modification) and it can cover many cases. Combine the regex/replace with a callback function to handle your extra replacements:
var replaceCallback = function(match) {
// if the match's first characters are '[code]', we have a '[code][/code]' block
if (match.substring(0, 6) == '[code]') {
// do any special replacements on this block; by default, return it untouched
return match;
}
// the match you now have is an HTML tag; it can be `<tag>` or `</tag>`
// do any special replacements; by default, return an empty string
return '';
}
str = str.replace(/(\[code\][\s\S]*?\[\/code\])|(<[\s\S]*?>)/g, replaceCallback);
The one regex modification was to add a group around the html-tag section (the second part of the regex). This will allow it to be passed to the callback function.
UPDATE ([code] isn't literal)
Per a comment, I've realized that the tag [code] isn't literal - you want to cover all BBCode style tags. This is just-as-easy as the above example (even easier in the callback). Instead of the word code in the regex, you can use [a-z]+ to cover all alphabetical characters. Then, inside the callback you can just check the very first character; if it's a [, you're in a code block - otherwise you have an HTML tag that's outside a code block:
var replaceCallback = function(match) {
// if the match's first character is '[', we have a '[code][/code]' block
if (match.substring(0, 1) == '[') {
// do any special replacements on this block; by default, return it untouched
return match;
}
// the match you now have is an HTML tag; it can be `<tag>` or `</tag>`
// do any special replacements; by default, return an empty string
return '';
}
str = str.replace(/(\[[a-z]+\][\s\S]*?\[\/[a-z]+\])|(<[\s\S]*?>)/gi, replaceCallback);
Also note that I added an i to the regex's options to ignore case (otherwise you'll need [a-zA-Z] to handle capital letters).
Here's my edited answer. Sorry again.
str = str.replace(/(\[code\])(.*?)(\[\/code\])/gm,function(a,b,c,d) {
return b + c.replace(/</g,'<').replace(/>/g,'>') + d;
});

How to force breaking of non breakable strings?

I have an HTML page that I generate from the data contained in a database. The database sometimes contains long strings that the browser can't break because the strings don't contain breakable characters (space, point, comma, etc...).
Is there any way to fix this using html, css or even javascript?
See this link for an example of the problem.
Yes you can, just set the css property of the box to:
.some_selector {
word-wrap: break-word;
}
Edit: Some testing shows that it does work with a div or a p - a block level element - but it does not work with a table cell, nor when the div is put inside a table cell.
Tested and works in IE6, IE7, IE8, Firefox 3.5.3 and Chrome.
Works:
<div style="word-wrap: break-word">aaaaaaaaaaaaaaaaaaaaaaddddddddddddddddddddddddddddddddddddddddddaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa </div>
Based on this article and this one as well: the "Shy Hyphen" or "Soft Hyphen" can be written in HTML as: ­ / ­ / &#xAD (173 dec = AD hex). They all convert to the U+00AD character.
The JavaScript textContent and nodeValue of the DOM Text Nodes are not 'entity encoded' - they just contain the actual entities. In order to write these characters you must therefore encode them yourself: \xAD is a simple way to write the same character in a JavaScript string. String.fromCharCode(173) would also work.
Based on your own VERY good answer - a jQuery Plugin version:
$.fn.replaceInText = function(oldText, newText) {
// contents() gets all child dom nodes -- each lets us operate on them
this.contents().each(function() {
if (this.nodeType == 3) { // text node found, do the replacement
if (this.textContent) {
this.textContent = this.textContent.replace(oldText, newText);
} else { // support to IE
this.nodeValue = this.nodeValue.replace(oldText, newText);
}
} else {
// other types of nodes - scan them for same replace
$(this).replaceInText(oldText, newText);
}
});
return this;
};
$(function() {
$('div').replaceInText(/\w{10}/g, "$&\xAD");
});
A side note:
I think that the place this should happen is NOT in JavaScript - it should be in the server side code. If this is only a page used to display data- you could easily do a similar regexp replace on the text before it is sent to the browser. However the JavaScript solution offers one advantage(or disadvantage depending on how you want to look at it) - It doesn't add any extraneous characters to the data until the script executes, which means any robots crawling your HTML output for data wont see the shy hyphens. Although the HTML spec interprets it as a "hyphenation hint" and an invisible character its not guaranteed across the rest of the Unicode world: (quote from Unicode standard via the second article I linked)
U+00AD soft hyphen indicates a
hyphenation point, where a line-break
is preferred when a word is to be
hyphenated. Depending on the script,
the visible rendering of this
character when a line break occurs may
differ (for example, in some scripts
it is rendered as a hyphen -, while in
others it may be invisible).
Another Note:
Found in this other SO Question - it seems that the "Zero Width Space" character ​ / ​ / U+200b is another option you might want to explore. It would be \x20\x0b as a javascript string.
As it has been pointed out numerous times, no, there is nothing you can do about it, without preprocessing the strings programmatically before displaying them.
I know there is a strategy with inserting the soft hyphen character (­), where needed, but does not seem like a popular option.
Check out this question: Soft hyphen in HTML ( vs. ­)
It is also possible to use word-break css property to cut every word on the element edge.
.selector_name {
word-break: break-all;
}
<p class="selector_name">some words some words some words some words</p>
you can obtain:
some word|
s some wo|<-edge of the element
rds some |
words som|
e words |
There is special character ­ or ­ that could do it.
For example:
Dzie­le­nie wy­ra­zów
could be display like:
1. dzie
2. le
3. nie wy
5. ra
6. zow
I'm answering my own question here...
Based on your answers, I came up with this solution (thanks to #CMS in this question for his help).
This script breaks any word that is more than 30 characters long by inserting a space at the 31st position.
Here is the fixed version: link
I have one problem left, I'd rather insert a ­ then a space. But the assigning node.nodeValue or node.textContent causes the insertion of the text ­ not the tag.
<script type="text/javascript">
$(function() {
replaceText(/\w{30}/g, "$& ", document.body);
});
function replaceText(oldText, newText, node) {
node = node || document.body; // base node
var childs = node.childNodes, i = 0;
while (node = childs[i]) {
if (node.nodeType == 3) { // text node found, do the replacement
if (node.textContent) {
node.textContent = node.textContent.replace(oldText, newText);
} else { // support to IE
node.nodeValue = node.nodeValue.replace(oldText, newText);
}
} else { // not a text mode, look forward
replaceText(oldText, newText, node);
}
i++;
}
}
</script>
I'll wait a few days before I accept this answer in case someone comes up with a simpler solution.
Thanks
The issue with using ­ and the solutions above is that an extra character is still there, and with a copy/paste action (even in plain text) it comes out.
I would use instead the tag <wbr> that is not visible and is not considered when copying.
For example, to have email addresses break in two lines (only when there is not enough space) I use this:
echo str_replace( "#","<wbr>#", $email );
That results in something like this:
name.surname
#website.com
You can use jQuery to achieve that, but How : Let me explain a little bit. First you need to add the reference and there is a plug-in which may help you : Read More Plugin - JQuery But you need to penetrate your code during the fetch phase. At this point you can handle this problem in HttpHandler or Page_PreInit phase but w/o any server side code it must be hard or perhaps there isn't any way. I don't know but you should be able to add something in your database-fetched html page.
It's easier to break up the long words from a text string, before you add them to the document.
It would also be nice to avoid orphans, where you have only one or two characters on the last line.
This method will insert spaces in every unspaced run of characters longer than n,
splitting it so that there are at least min characters on the last line.
function breakwords(text, n, min){
var L= text.length;
n= n || 20;
min= min || 2;
while(L%n && L%n<min)--n;
var Rx= RegExp('(\\w{'+n+',}?)','g');
text= text.replace(Rx,'$1 ');
return text;
}
//test
var n=30, min=5;
var txt= 'abcdefghijklmnopqrstuvwxyz0123456789 abcdefghijklmnopqrstuvwxyz012345678 abcdefghijklmnopqrstuvwxyz01234567 abcdefghijklmnopqrstuvwxyz0123456';
txt=txt.replace(/(\w{30,})/g,function(w){return breakwords(w,n,min)});
alert(txt.replace(/ +/g,'\n'))
/* returned value: (String)
abcdefghijklmnopqrstuvwxyz0123
456789
abcdefghijklmnopqrstuvwxyz0123
45678
abcdefghijklmnopqrstuvwxyz012
34567
abcdefghijklmnopqrstuvwxyz01
23456
*/

Categories