JQuery detect newline in a string - javascript

A "str" variable in JavaScript return by a backend contains a string with a few paragraphs separated by line breakers.. When I do this:
console.log(str);
the Firefox console displays:
"This is paragraph 1.
This is paragraph2.
This is paragraph3"
The problem is, this str is NOT separated by a "\n" character. It's just separated by invisible linebreaks, as you can see in the console output. Is there any way to detect this line break? What I'm eventually trying to do is replace these invisible line breaks with a "br" tag so that I can append it inside the html document..
Is there a way to do this?
Thanks
(Unfortunately, there is no way to change the backend..)

Take a look at nl2br on php.js which seems exactly what you're looking for. Basically, it's:
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');
}
Demo : http://devilmaycode.altervista.org/jquery-convert-line-breaks-to-br-nl2br-equivalent/

var text = "This is paragraph 1.
This is paragraph2.
This is paragraph3";
var matches = text.match(/\n/g);
var new_lines = matches ? matches.length : 0; //Get no. of new line here
Demo

As an alternative thought (and if possible in your situation), because you essentially want to render the text in HTML with the line-breaks preserved, you can make use of CSS to do this for you. Take a look at the the white-space property with a value of pre-line or pre-wrap:
Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks -
W3Schools
So, if you append the string to the DOM as a paragraph like:
<p class="preserveLineBreaks">This is paragraph 1.
This is paragraph2.
This is paragraph3<p>
Then with a simple CSS selector as follows, you'll get the expected result:
.preserveLineBreaks {
white-space: pre-line; //or pre-wrap
}

Actually, the "invisible line breaks" in the Firefox console are the \n characters. I've included a line to confirm this in the code below. In addition, browsers will generally ignore the \n character in favor of the <br/> and so the str variable that you have should display nicely as one line. To however identify the "\n" chars and replace them with <br />, try this
<span id="someText">This is
some text
that I need
to modify
</span>
<script>
var text = document.getElementById("someText") ;
alert(text.innerHTML.match(/\n/g).length) ; // confirm \n are in var
alert (text.innerHTML) ;
var withBRs = text.innerHTML.replace(/\n/g, "<br />") ;
text.innerHTML = withBRs ;
</script>

Related

How to add a new line in MySql when user hits 'enter' in textarea? [duplicate]

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?
Example:
A variable passed from PHP as below:
"This is man.
Man like dog.
Man like to drink.
Man is the king."
I would like my result to look something like this after the JavaScript converts it:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
This will turn all returns into HTML
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169
https://stackoverflow.com/a/36524555/5042169
If your concern is just displaying linebreaks, you could do this with CSS.
<div style="white-space: pre-line">Some test
with linebreaks</div>
Jsfiddle: https://jsfiddle.net/5bvtL6do/2/
Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).
Without regex:
str = str.split("\n").join("<br />");
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
Shortest code supporting the most common EOL styles \r, \n, \r\n and using HTML5 <br>:
s.replace(/\r?\n|\r/g, '<br>')
Regardless of the system:
my_multiline_text.replace(/$/mg,'<br>');
It is also important to encode the rest of the text in order to protect from possible script injection attacks
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
This worked for me when value came from a TextBox:
string.replace(/\n|\r\n|\r/g, '<br/>');
For those of you who just want to allow max. 2 <br> in a row, you can use this:
let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');
First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br
Second line: Search for all single \r\n or \n and replace them with <br>
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm
this will help you everytime.
Not answering the specific question, but I am sure this will help someone...
If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:
var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
I had a config in PHP that was being passed in from the Controller. (Laravel)
Example: PHP Config
'TEXT_MESSAGE' => 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
Then in javascript using es6 reduce. notice I had to have two \\ or the output was not being replace correctly. Here are the parameters that are assoicated with the reduce function
previousValue (the value resulting from the previous call to
callbackfn)
currentValue (the value of the current element)
currentIndex Optional
array (the array to traverse) Optional
//p is previousVal
//c is currentVal
String.prototype.newLineReplace = function(){
return [...arguments].reduce((p,c) => p.replace(/\\n/g,c), this);
}
Here is how i used it in my script.
<script type="text/javascript">var config = #json($config);</script>
config.TEXT_MESSAGE.newLineReplace("<br />")
of course you could just called it on a javascript sring like...
let a = 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
var newA = a.newLineReplace("<br />")
//output
'From:Us<br />User: Call (1800) 999-9999<br />userID: %s'

Why does getting value from data-attribute affect the text

I'm struggling with some syntax, mostly why the data-attribute(HTML5) is affecting the text in the way it is.
Please consider this example which does what is expected
<div id="s"></div>
<script>
var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;
</script>
The result is I see 2 lines in HTML due to the \n. This is expected
The task means I need to change the way we work into
<div id="s" data-txt="this is it\nand done"></div>
<script>
var ele = document.getElementById("s");
var txt = ele.getAttribute("data-txt");
ele.innerText = txt;
</script>
Note we're now using the data attribute of data-txt. The issue is this renders the text verbatim, meaning I see 1 line: this is it\nand done
https://jsfiddle.net/he4ydvva/
The fact I can't even use replace (ele.getAttribute("data-txt").replace('\n','blah');) suggests that although I see \n, the computer is reading something different (maybe the charcode value or similar)
Why does this happen and how do I prevent it?
Edit
I have seen How can I insert new line/carriage returns into an element.textContent? but this won't suffice as I need the string to exist within the data-txt and concatenating as "this is " + String.fromCharCode(13) + " is not valid for HTML5
You are confusing HTML with JavaScript.
\n is a JavaScript character. data-* attributes are HTML. For inserting newline in HTML, you should use the HTML entity
(Newline) or 
 (carriage return) or their combination.
HTML doesn't understand \n, \r and so on.
Also note,
<div>This is a line \n Another one</div>
This won't insert newline but the code below will:
<div>This is a line
Another one</div>
Check out the full list of HTML entities
Here's what you should use:
ele = document.getElementById("t");
txt = ele.getAttribute("data-txt").replace(/\\n/g,'<br>');
ele.innerHTML = txt;
Explanation:
The \ char is an escape character and so to specify a new line, you need to use two \\ so that the 1st one escapes the meaning of the second. The second one is then treated as a normal char and is read together with the n as \n.
Further, you must replace that with a <br> because a browser will not respect CRLF chars.
Here is your example on jsfiddle fixed: https://jsfiddle.net/4eurrzgx/
var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;
ele = document.getElementById("t");
txt = ele.getAttribute("data-txt").replace(/\\n/,'<br>');
ele.innerHTML = txt;
<div id="s"></div>
<p>
***
</p>
<div id="t" data-txt="this is it\nand done"></div>

How to display text inside text area with line break instead of <br/> [duplicate]

I want to add a newline in a textarea. I tried with \n and <br/> tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?
<textarea cols='60' rows='8'>This is my statement one.\n This is my statement2</textarea>
<textarea cols='60' rows='8'>This is my statement one.<br/> This is my statement2</textarea>
Try this one:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Line Feed and 
 Carriage Return are HTML entitieswikipedia. This way you are actually parsing the new line ("\n") rather than displaying it as text.
Break enter Keyword line in Textarea using CSS:
white-space: pre-wrap;
I think you are confusing the syntax of different languages.
is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).
\n is the linefeed character literal (ASCII 10) in a Javascript string.
<br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.
Hopefully the following illustration will make it clearer:
T.innerText = "Position of LF: " + t.value.indexOf("\n");
p1.innerHTML = t.value;
p2.innerHTML = t.value.replace("\n", "<br/>");
p3.innerText = t.value.replace("\n", "<br/>");
<textarea id="t">Line 1
Line 2</textarea>
<p id='T'></p>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>
A few points to note about Html:
The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
The P element renders all contiguous white spaces (including new lines) as one space.
The LF character does not render to a new line or line break in HTML.
The TEXTAREA renders LF as a new line inside the text area box.
I've found String.fromCharCode(13, 10) helpful when using view engines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:
viewHelper.js
exports.replaceNewline = function(input) {
var newline = String.fromCharCode(13, 10);
return input.replaceAll('\\n', newline);
}
EJS
<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>
Renders
<textarea>Blah
blah
blah</textarea>
replaceAll:
String.prototype.replaceAll = function (find, replace) {
var result = this;
do {
var split = result.split(find);
result = split.join(replace);
} while (split.length > 1);
return result;
};
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.
If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from #Bakudan:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Try this. It works:
<textarea id="test" cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Replacing for <br> tags:
$("textarea#test").val(replace($("textarea#test").val(), "<br>", "
")));
To get a new line inside text-area, put an actual line-break there:
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
You might want to use \n instead of /n.
After lots of tests, following code works for me in Typescreipt
export function ReplaceNewline(input: string) {
var newline = String.fromCharCode(13, 10);
return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
You should also check the css white-space property (mdn docs) of your element, make sure it's set to a value that doesn't suppress line breaks, e.g.:
white-space: pre-line;
You'd be interested in these 3 values:
pre
Sequences of white space are preserved. Lines are only broken at
newline characters in the source and at <br> elements.
pre-wrap
Sequences of white space are preserved. Lines are broken at
newline characters, at <br>, and as necessary to fill line boxes.
pre-line Sequences of white space are collapsed. Lines are broken at
newline characters, at <br>, and as necessary to fill line boxes.
My .replace()function using the patterns described on the other answers did not work. The pattern that worked for my case was:
var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'
');
// str: "Test
Test
Test"
T.innerText = "Position of LF: " + t.value.indexOf("\n");
p3.innerText = t.value.replace("\n", "");
<textarea id="t">Line 1
Line 2</textarea>
<p id='p3'></p>
If you are using react
Inside the function
const handleChange=(e)=>{
const name = e.target.name;
let value = e.target.value;
value = value.split('\n').map(str => <span>{str}<br/></span>);
SetFileds({ ...fileds, [name]: value });
}
A simple and natural solution not involving CSS styles or numeric character references like
would be to use the &NewLine; character entity reference:
The cardinal directions are:&NewLine;- North&NewLine;- East&NewLine;- South&NewLine;- West
Note: Since this is defined simply as the LF (line feed, or the U+000A Unicode code point) character, it's not 100% certain whether it suits situations where the entire CR + LF (carriage return + line feed) sequence is required. But then, it worked in my Chrome, Edge and WebView2 tests done on Windows 10, so it should be ok to use.
just use <br>
ex:
<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf
</textarea>
result:
blablablabla kakakakakak fafafafafaf

Removing non-break-spaces in JavaScript

I am having trouble removing spaces from a string. First I am converting the div to text(); to remove the tags (which works) and then I'm trying to remove the "&nbsp" part of the string, but it won't work. Any Idea what I'm doing wrong.
newStr = $('#myDiv').text();
newStr = newStr.replace(/ /g, '');
$('#myText').val(newStr);
<html>
<div id = "myDiv"><p>remove space</p></div>
<input type = "text" id = "myText" />
</html>
When you use the text function, you're not getting HTML, but text: the entities have been changed to spaces.
So simply replace spaces:
var str = " a     b   ", // bunch of NBSPs
newStr = str.replace(/\s/g,'');
console.log(newStr)
If you want to replace only the spaces coming from do the replacement before the conversion to text:
newStr = $($('#myDiv').html().replace(/ /g,'')).text();
.text()/textContent do not contain HTML entities (such as ), these are returned as literal characters. Here's a regular expression using the non-breaking space Unicode escape sequence:
var newStr = $('#myDiv').text().replace(/\u00A0/g, '');
$('#myText').val(newStr);
Demo
It is also possible to use a literal non-breaking space character instead of the escape sequence in the Regex, however I find the escape sequence more clear in this case. Nothing that a comment wouldn't solve, though.
It is also possible to use .html()/innerHTML to retrieve the HTML containing HTML entities, as in #Dystroy's answer.
Below is my original answer, where I've misinterpreted OP's use case. I'll leave it here in case anyone needs to remove from DOM elements' text content
[...] However, be aware that re-setting the .html()/innerHTML of an element means trashing out all of the listeners and data associated with it.
So here's a recursive solution that only alters the text content of text nodes, without reparsing HTML nor any side effects.
function removeNbsp($el) {
$el.contents().each(function() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace(/\u00A0/g, '');
} else {
removeNbsp( $(this) );
}
});
}
removeNbsp( $('#myDiv') );
Demo

Textarea \n to <br> without escaping

I am entering stuff in a textarea, and after I press a button, my JS takes the textarea input and puts it inside a div tag.
The problem is, when I enter a newline in the textarea, like so:
Hi
Goodbye
It comes out in the div as
Hi<br><br>Goodbye
When I use Firebug to inspect the actual HTML markup live, I see this in the div:
Hi<br> <br> Goodbye
This is a function I found that should replace the newlines with breaktags:
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');
}
Here is how I use it:
etext = $('#mytext').val();
etext = nl2br(etext,false);
$('#mydiv').text(etext);
However as you see, it is not working.
How can I do this? If you need more code, do let me know
Perhaps it will work if you do:
$('#mydiv').html(etext);
...or with no framework:
document.getElementById("mydiv").innerHTML = etext;
The problem is that text() is automatically escaping your markup characters:
We need to be aware that this method escapes the string provided as
necessary so that it will render correctly in HTML. To do so, it calls
the DOM method .createTextNode(), which replaces special characters
with their HTML entity equivalents (such as < for <).

Categories

Resources