Becky
Becky

Reputation: 5585

Adding breaks using replace()

I've got a text input and a div that contains the same text. I'm trying to make the line breaks in the DIV text same as in the input text. So I used .replace(/\n/g to do this. The replace successfully identify the line breaks in the textarea and is able to add <br> accordingly. But the <br> does not do a line break, it is a part of the text string?

How do I make the <br> do a line break?

See example:

<textarea id="ab">
Test
Line breaks
on blur
</textarea>

<div id="divTx"><div>

.on("blur", ".ab", function() {
    $('#divTx').text($('#ab').val().replace(/\n/g, '<br />') );
});

DIV (.divTx) output:

Test<br> Line breaks<br>on blur<br> // <br> doesn't do line break

Upvotes: 1

Views: 115

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to use .html(htmlString)

Set the HTML contents of each element in the set of matched elements.

Use

$('#divTx').html($('#ab').val().replace(/\n/g, '<br />'))

Upvotes: 4

Related Questions