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>');
Related
I have a piece of text that comes from the backend with /n string in it, but I hope I can replace this with
a lot of ways I found on the Internet, but I still can't replace it with a label smoothly, does anyone know the reason Caused?
Thanks for your help.
let demo = document.querySelector('.demo').textContent;
console.log(demo)
demo.replace(new RegExp('\r?\n','g'), '<br />');
<p class="demo">尚有 1 個職缺使用母公司的點數,\n關閉後才可解除綁定</p>
const demoEl = document.querySelector('.demo')
demoEl.innerHTML = demoEl.textContent.replace(/\\n/g, '<br />');
<p class="demo">尚有 1 個職缺使用母公司的點數,\n關閉後才可解除綁定</p>
A couple of points:
Your text doesn't include a new line character so you need to match for the character combination of \n like so... /\\n/g
Your just replacing the content reference, you need to apply the replace to the elements innerHTML
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'
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'
Having a lot of difficulties using regex.
Heres what i am trying to do...
text<div> text </div><div> text </div><div> text </div>
to turn it in to
text<br> text<br>text<br>text
I've tryed doing...
newhtml = newhtml.replace(/\<div>/g,'<br>');
newhtml = newhtml.replace(/\</div>/g,' ');
but this gives the wrong output. Does jquery provide a better way of doing this?
That's because you're escaping the wrong thing, as only the backslash needs to be escaped.
newhtml = newhtml.replace(/<div>/g,'<br>');
newhtml = newhtml.replace(/<\/div>/g,' ');
Yes you are correct, jQuery does provide a better way of doing this.
An interesting read
first.
Easy, elegant, solution to your specific problem.
$('div').replaceWith(function(){
return "<br>"+$(this).html();
});
jsFiddle
Don't use regexes if you don't need them; just replace string literals.
text.replace("<div>","<br>").replace("</div>","");
Note: This solution applies exactly to this scenario, I don't normally have anything against using regular expresions.
This must do the job:
text.replace(/(<\/?\w+?>)\s*?(<\/?\w+?>)|(<\/?\w+?>)/g,'<br>')
Though this will only work if there were no tags with some attributes like <div id="foo1">
You do not need to escape < as you did in your example, but instead you do need to escape /
A simple way to do this is the following:
$('.container').html(function(i, html) {
return html.replace(/<(|\/)div>/g, function(match) {
return match == '<div>' ? '<br>' : '';
});
});
/<(|\/)div>/: Matches <div> or </div>.
demo
Note: .container is where your html is placed.
One Liner using JQuery
newhtml = $(newhtml ).text().split(' ').join('<br/>');
You can achieve this using a simple RegExp
output = inputText.replace(/<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, "With whatever you want it to be replaced with")
Or you can do this
String.prototype.replaceTags = function( replacementText )
{
var x = new RegExp( "(" + replacementText + ")+" , "ig");
return this
.replace( /<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, replacementText )
.replace( x, replacementText )
}
And then call it directly on the String as follows
"text<div> text </div><div> text </div><div> text </div>".replaceTags( "<br>" )
You'll get this -- "text<br> text <br> text <br> text <br>"
This will search for portions in the string which begin with the "<" contains some text in between "div/p/br" additionally if the tag is being ended by "/" and finally the ">" closing of the tag. The ignore case will help when you are not sure that the element is written in Upper or Lower case.
I'm trying to take some parsed XML data, search it for instances of the tag and replace that tag (and anything that may be inside the font tag), and replace it with a simple tag.
This is how I've been doing my regexes:
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/; //Test against valid email
console.log('regex: ' + emailReg.test(testString));
and so I figured the font regex would be something like this:
var fontReg = /'<'+font+'[^><]*>|<.'+font+'[^><]*>','g'/;
console.log('regex: ' + fontReg.test(testString));
but that isn't working. Anyone know a way to do this? Or what I might be doing wrong in the code above?
I think namuol's answer will serve you better then any RegExp-based solution, but I also think the RegExp deserves some explanation.
JavaScript doesn't allow for interpolation of variable values in RegExp literals.
The quotations become literal character matches and the addition operators become 1-or-more quantifiers. So, your current regex becomes capable of matching these:
# left of the pipe `|`
'<'font'>
'<''''fontttt'>
# right of the pipe `|`
<#'font'>','g'
<#''''fontttttt'>','g'
But, it will not match these:
<font>
</font>
To inject a variable value into a RegExp, you'll need to use the constructor and string concat:
var fontReg = new RegExp('<' + font + '[^><]*>|<.' + font + '[^><]*>', 'g');
On the other hand, if you meant for literal font, then you just needed:
var fontReg = /<font[^><]*>|<.font[^><]*>/g;
Also, each of those can be shortened by using .?, allowing the halves to be combined:
var fontReg = new RegExp('<.?' + font + '[^><]*>', 'g');
var fontReg = /<.?font[^><]*>/g;
If I understand your problem correctly, this should replace all font tags with simple span tags using jQuery:
$('font').replaceWith(function () {
return $('<span>').append($(this).contents());
});
Here's a working fiddle: http://jsfiddle.net/RhLmk/2/