Opu Hossain Hawlader
Opu Hossain Hawlader

Reputation: 27

Add <br /> tag after end of every line in jQuery / JavaScript

I have a <textarea> field for user input. I want this - When user paste their text in that field and click some button it will automatic add a line break tag <br /> after the end of every line.
My html form look like this.

<div class="comment">
    <textarea class="form-control page_details" rows="5" id="text" placeholder="Detail here" name="details"></textarea>
    <button type="button">Generate</button>
</div>

and when user paste their text on textarea field like.

Lorem ipsum dolor sit amet,
consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt
ut laoreet dolore magna aliquam
erat volutpat.

When clicking the button it will look like this.

Lorem ipsum dolor sit amet, <br />
consectetuer adipiscing elit, <br />
sed diam nonummy nibh euismod tincidunt<br />
ut laoreet dolore magna aliquam<br />
erat volutpat.<br />

Help me out guys.

Upvotes: 3

Views: 6416

Answers (4)

Harish V
Harish V

Reputation: 681

I'd cover my bets by handling \r\n (the sequence), and then handling \rand \n through a character class, like this:

text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');

The first replace turns the sequence \r\n into <br />. The second replace replaces any \r or \n characters found on their own with the string.

More on regular expressions in JavaScript here.

Upvotes: 0

guest271314
guest271314

Reputation: 1

You could use String.protototype.split() with RegExp /\n|\s\n/ , Array.prototype.join() with parameter "<br>\n" , concatenate "<br>" to end of replacement textarea value

function addBreak(el) {
  var textarea = el;
  var matches = textarea.value.split(/\n|\s\n/);
  textarea.value = matches.join("<br>\n") + "<br>";
}
<div class="comment">
  <textarea class="form-control page_details" rows="5" id="text" placeholder="Detail here" name="details"></textarea>
  <button type="button" onclick="addBreak(this.previousElementSibling)">Generate</button>
</div>

Upvotes: 6

Arumuga Raja
Arumuga Raja

Reputation: 184

Replace the new line characters with <br/>

var pastedText = $("#text").val();
pastedText = pastedText.replace(/(\r\n|\n|\r)/gm, "<br>");

Upvotes: 0

sathish kumar
sathish kumar

Reputation: 936

Use on paste event.

$("button").on("click",function(){
  $("#text").bind("paste", function(e){
    $('#txtarea').append('<BR>').focus();
  });
});
<div class="comment">
    <textarea class="form-control page_details" rows="5" id="text" placeholder="Detail here" name="details"></textarea>
    <button type="button">Generate</button>
</div>

Upvotes: 0

Related Questions