Nl2Br() Equivalent in JavaScript

nl2br() equivalent in javascript

Take a look at nl2br on php.js which seems exactly what you're looking for. Basically, it's:

function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
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');
}

EDIT:
your example using nl2br() may be changed like this:

$('#TextArea').keypress(function(evt){
$('#TextArea1').html(nl2br($('#TextArea').val()));
});

(note that this updates #TextArea1 on every keypress and doesn't change the value of #TextArea wich is what I think you're looking for, but I might be misunderstanding)

EDIT2:
If you want to get the behaviour of your old function (with inserting <br/>s to #TextArea) do this:

$('#TextArea').keypress(function(evt){
$('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
$('#TextArea1').html($('#TextArea').val()); // copy to #TextArea1
});

jQuery convert line breaks to br (nl2br equivalent)

demo: http://so.devilmaycode.it/jquery-convert-line-breaks-to-br-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');
}
  • http://phpjs.org/functions/nl2br:480

How do I replace all line breaks in a string with br / elements?

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

How to replace \n with br / in JavaScript?

Replace with global scope

$('#input').val().replace(/\n/g, "<br />")

or

$('#input').val().replace("\n", "<br />", "g")

What's the easiest way to replace '\n' with 'br'?

PHP's built in function nl2br() does this.

Convert \n line breaks to HTML BR line breaks

You are trying to use a string method on an object, not on property values within that object.

There is no Object.replace() so that will throw error

Similarly undefined.replace() will also cause error

Presumably you only have to fix a few property values but first it is necessary to make sure those values are defined and are strings before using replace()

Try

function convertBreak(str){
if(!str){
return ''; // don't want `undefined` printing into page
}
// if it's something other than string, return it as is
if( typeof str !=== 'string'){
return str;
}else{
return str.replace(/\n/g, "<br />")
}
}

incident.Description = convertBreak(incident.Description);


Related Topics



Leave a reply



Submit