user3354539
user3354539

Reputation: 1245

jQuery - replace line break <br /> with new line \n

I am using jQuery 1.11.

I have a string displayed in html and I want that same string copied and pasted to a textarea.

The problem for me is that the string to be pasted contains a line break <br />. To correctly display the string in the textarea, I must replace the line break <br /> with a new line \n.

I am using replace, but each permutation I write to replace the <br /> with the \n fails. The string is printed along one line.

I have searched google & SO, but this just does not work for me - I am missing something basic here.

How can I write a string replace function to replace the <br /> with \n?

Here is my string:

[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />

Here is the replace code that does not work for me:

var text = $(this).closest('.employment_history_suggestion_add_button').prev().text();  // Get text of the previous span element
text = text.replace(/<br\s*\/?>/mg,"\n");  // replace line break with new line for correct display in textarea.

EDIT

This is the code that now works.

I was using the .text() - should have been using the .html().

I was using \\n - should have been using \n.

var text = $(this).closest('.employment_history_suggestion_add_button').prev().html();  // Get html of the copied string (keep the line breaks for replacing with new lines).
text = text.replace(/<br\s*\/?>/gim, "\\n");
$('#id_employment_history_employerTA').val(function (i, oldVal) {
                return oldVal + text;  // append the value of text to the textarea.
});

I hope that this helps someone.

Upvotes: 1

Views: 4739

Answers (1)

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47159

It's unclear which part of your code is failing, although you'll want to double escape the \n carriage return in your replace pattern:

var text = '[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />'

text = text.replace(/<br\s*\/?>/gim, "\\n")
alert(text);

Result:

[employer]\n[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)\n\n

Upvotes: 5

Related Questions