Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery javascript regex Replace <br> with \n

How do i write a regex to replace <br /> or <br> with \n. I'm trying to move text from div to textarea, but don't want <br>'s to show in the textarea, so i want to replace then with \n.

like image 963
Pinkie Avatar asked May 11 '11 04:05

Pinkie


People also ask

How do you replace Br?

In the opening Find and Replace dialog box, click on the Find what box and press the Ctrl + Shift + J keys together, enter br into the Replace with box, and then click the Replace All button.

What is replace in jQuery?

replaceWith( newContent )Returns: jQuery. Description: Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.


2 Answers

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example

edit: added i flag

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

like image 190
Teneff Avatar answered Oct 20 '22 11:10

Teneff


myString.replace(/<br ?\/?>/g, "\n")

like image 39
Adam Bergmark Avatar answered Oct 20 '22 11:10

Adam Bergmark