How do i write a regex to replace
or
with \\n
. I\'m trying to move text from div to textarea, but don\'t want
myString.replace(/<br ?\/?>/g, "\n")
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>
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" />
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
a cheap and nasty would be:
jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")
EDIT
jQuery("#myTextArea").val(
jQuery("#myDiv").html()
.replace(/\<br\>/g, "\n")
.replace(/\<br \/\>/g, "\n")
);
Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/