admin管理员组文章数量:1125727
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."
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."
Share
Improve this question
edited Mar 23, 2020 at 19:47
John
13.7k14 gold badges109 silver badges189 bronze badges
asked Apr 24, 2009 at 4:38
Jin YongJin Yong
43.7k72 gold badges144 silver badges193 bronze badges
5
- 1 Something wrong with your original question? stackoverflow.com/questions/784313/… – harto Commented Apr 24, 2009 at 4:42
- 1 You could also do nl2br($string) in PHP before you send it to JavaScript. – alex Commented Apr 24, 2009 at 4:44
- 1 I'm going to vote to close the earlier question, as this has a better example. – eyelidlessness Commented Apr 24, 2009 at 4:48
- 2 He should edit the initial question then – nickf Commented Apr 24, 2009 at 4:48
- I came here from a misguided understanding to what was going on with .text(). See stackoverflow.com/q/35238362/1467396 if that's what you're doing, too – David Commented Aug 14, 2019 at 21:54
14 Answers
Reset to default 1540This 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>')
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'));
}
}
}
Regardless of the system:
my_multiline_text.replace(/$/mg,'<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'
本文标签: javascriptHow do I replace all line breaks in a string with ltbr gt elementsStack Overflow
版权声明:本文标题:javascript - How do I replace all line breaks in a string with <br > elements? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736674517a1947108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论